在 raspberry pi pico 中分离 python 代码

Sepreating python code in raspberry pi pico

我无法在 raspberry pi pico 上从 micro python 中的不同文件导入 class。

例如。 目录结构

目录/
|__main.py
|__imports/
|_example.py

文件名:main.py


from imports.example import ex

a = ex("name")
a.print_name()

文件名:example.py


class ex:
    def __init__(self, name):
        self.name = name

    def print_name(self):
        print(self.name)

报错如下

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ImportError: no module named 'imports.example'

当所有 classes 都存在于同一个文件中时,该代码有效。我在 debain 上使用 pico-go vscode 扩展。我尝试在示例目录中添加 __ init __.py,但没有成功。

您在 imports 目录中缺少一个空的 __init__.py 文件,它会“神奇地”(实际上,按照惯例)将 imports 变成一个包。

https://docs.python.org/3.8/tutorial/modules.html#packages

dir/
   main.py
   imports/
        __init__.py     # <= turns 'imports' into a package
        example.py
$ python main.py
name

Run 按钮代表 Run current file。 因此,只上传main.py。 导入将失败,因为 example.py 未上传。

Select Pico-Go > Upload Project 来自 All commands 上传 example.py 到 pico。 然后点击Run,执行main.py,导入成功

环境

  • vscode (1.65.2)
  • Pico-Go (v1.4.3)