Saturday, April 2, 2022

[SOLVED] Sepreating python code in raspberry pi pico

Issue

I am unable to import class from a different file in micro python on raspberry pi pico.

Eg. directory structure

dir/
  |__main.py
  |__imports/
    |_example.py

filename : main.py


from imports.example import ex

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

filename : 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. I tried adding __ init __.py in the example directory, but no luck.


Solution

The Run button stands for Run current file. Therefore, only main.py is uploaded. The import will fail because example.py is not uploaded.

Select Pico-Go > Upload Project from All commands for upload example.py to pico. Then click Run and execute main.py, the import will be successful.

Environment

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


Answered By - あまみや
Answer Checked By - Marie Seifert (WPSolving Admin)