not logged in | [Login]

Importing your own modules using MicroPython uses very similar techniques to importing modules with CPython. This page will try to cover the quirks and give some examples.

CPython looks for modules using sys.path.

MicroPython also looks for modules using sys.path, however, sys.path is initialized a little differently than it is in CPython. MicroPython also doesn't have a notion of "current directory", so relative imports don't work.

Let's see where MicroPython looks for modules:

>>> import sys
>>> sys.path
['0:/', '0:/lib']

On the pyboard, 0:/ refers to the internal flash, and 1:/ refers to the sdcard.

There are 2 ways of creating modules: the first is to put your module into a file, and the second, is to put your module in a directory. So lets create a file, mod1.py which contains the following:

def hello():
    print('hello from mod1')
and copy it to your internal flash. Note that you'll most likely need to restart micropython in order for it to see the new file. The simplest way of doing this is to press Control-D from the REPL. You can also press the RST (aka Reset) pushbutton. Now you can do:
>>> import mod1
>>> mod1.hello()
hello from mod1
You can also put your module in a directory. In this case, python expects to find a file called __init__.py inside a directory with the name of the module. So we'll create a directory called mod2 at the root of the internal flash, and create an __init__.py file with the following contents:
def hello():
    print('hello from mod2')
Press Control-D to restart micropython and you can now do:
>>> import mod2
>>> mod2.hello()
hello from mod2

What if you want to get your modules from the sdcard? Lets create mod3.py

def hello():
    print('hello from mod3')
and make a directory called mod4 with the following __init__.py inside it:
def hello():
    print('hello from mod4')
and copy these to the sdcard. Restart micropython and:
>>> import mod3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'mod3'
Oops. What happened? MicroPython followed through sys.path and looked for 0:/mod3.py, 0:/mod3/__init__.py, 0:/lib/mod3.py, and 0:/lib/mod3/__init__.py and couldn't find any of those.

We need to modify sys.path to also look on the sdcard.

>>> import sys
>>> sys.path.append('1:/')
>>> import mod3
>>> mod3.hello()
hello from mod3
>>> import mod4
>>> mod4.hello()
hello from mod4

Note: there is a possibility that the 0:/ and 1:/ may be changed to /flash/ and /sd/ (or something similar), in which case these instructions will need to be amended. If in doubt, check sys.path and see what it looks like.