简体   繁体   English

在树莓派 pico 中分离 python 代码

[英]Sepreating python code in raspberry pi pico

I am unable to import class from a different file in micro python on raspberry pi pico.我无法从树莓派 pico 上的微型 python 中的不同文件导入 class。

Eg.例如。 directory structure目录结构

dir/目录/
|__main.py |__main.py
|__imports/ |__进口/
|_example.py |_example.py

filename: main.py文件名:main.py


from imports.example import ex

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

filename: example.py文件名:example.py


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

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

The error states as following错误状态如下

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

The code works when all the classes are present inside the same file.当所有类都存在于同一个文件中时,该代码有效。 I am using pico-go vscode extension on debain.我在 debain 上使用 pico-go vscode 扩展。 I tried adding __ init __.py in the example directory, but no luck.我尝试在示例目录中添加 __ init __.py,但没有成功。

The Run button stands for Run current file . Run按钮代表Run current file Therefore, only main.py is uploaded.因此,只上传main.py。 The import will fail because example.py is not uploaded.导入将失败,因为未上传 example.py。

Select Pico-Go > Upload Project from All commands for upload example.py to pico. Select Pico-Go > Upload ProjectAll commands上传项目,将example.py上传到 pico。 Then click Run and execute main.py, the import will be successful.然后点击Run ,执行main.py,导入成功。

Environment环境

  • vscode (1.65.2) vs代码(1.65.2)
  • Pico-Go (v1.4.3)皮克围棋 (v1.4.3)

You are missing an empty __init__.py file in the imports directory, which would "magically" (by convention, actually) turn imports into a package.您在imports目录中缺少一个空的__init__.py文件,它会“神奇地”(实际上,按照惯例)将imports转换为 package。

https://docs.python.org/3.8/tutorial/modules.html#packages 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM