Issues when importing a custom module into my MicroPython Pico-W Project

198 views Asked by At

I am very inexperineced and new when it comes to file structures of things like this. I am currently messing around with MicroPython and the Pico-W. I am trying to import a module from another python file but I keep getting this error:

Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: no module named 'foo'

Currently my file structure looks like this:

my-proj:
 - main.py
 - foo.py

and my code like this:

main.py
________

from foo import bar

bar()
foo.py
________

def bar():
print('foobar')

I have tried moving things in and out of folders, separating them, installing them to the Pico-W, etc. Can't seem to figure it out and I am sure it's simple and I am just blind to it.

Thanks for any help.

2

There are 2 answers

0
Jiu_Zou On

you need go to my-proj first.

cd my-proj
python foo.py

or add to the environment variables.

foo.py
---------
import sys
import os
abspath = os.path.abspath(__file__)
filename = abspath.split(os.sep)[-1]
abspath = abspath.replace(filename, "")
sys.path.append(abspath)
0
brainelectronics On

On a MicroPython device the main.py and boot.py files are located in the "root".

Additional files should be placed inside the lib directory.

pyboard/
├── lib
│   ├── foo.py
├── boot.py
├── main.py

You can check the MicroPython default sys path with

import sys
print(sys.path)

With that you can use this as main.py

from foo import bar

bar()

and the following as lib/foo.py

def bar():
    print('foobar')