Page 1 of 1

[SOLVED] import module from filesystem

Posted: Wed Aug 08, 2018 1:46 pm
by yeyeto2788
Hello guys,

I'm currently working on a project that involve importing selected modules (https://github.com/yeyeto2788/MicroPythonScripts) that are already in the filesystem.

So let's say I have my script call `menu.py` and it will get all files on the filesystem and if I select one of them I want that module to be executed.

Files in the filesystem:
  • menu.py
  • boot.py
  • test.py
  • abs.py
This is the code on the `menu.py` to get the files and try to import the module from the filesystem:

Code: Select all

import time,  os
def get_files():
    extensions = ".py"
    excluded_files = ["main.py", "boot.py"]
    dirfiles = []
    for filename in os.listdir():
        if filename.lower().endswith(extensions):
            if filename.lower() not in excluded_files:
                dirfiles.append(filename.replace(extensions, ""))
    return dirfiles
a = get_files()[1]
import a
a.show()    
So this function will give the `test.py` and the `abs.py` and import the `test.py` script and execute the function `show()` on it which is simply prints a string:

Code: Select all

print("wujuuuu imported!")

I get an error saying the following:

Code: Select all

 b'Traceback (most recent call last):\r\n  File "<stdin>", line 12, in <module>\r\nImportError: no module named \'a\'\r\n')
Is there any possible solution for this? or anyone that could help me out with this?

Re: import module from filesystem

Posted: Wed Aug 08, 2018 4:39 pm
by Christian Walther
The import statement takes a name, not an expression. You want the __import__ function (ignore the reference to importlib, it doesn’t exist on MicroPython).

See https://github.com/pewpew-game/pewpew/b ... es/menu.py for a working example of the exact thing you want to do. It’s in CircuitPython, but the relevant part (last few lines) translates to MicroPython unchanged.

Re: import module from filesystem

Posted: Mon Aug 13, 2018 10:39 am
by yeyeto2788
Wujuuuu! It worked like a charm :D .

Thank you very much for the help!

Regards.

Re: [SOLVED] import module from filesystem

Posted: Thu Dec 12, 2019 5:28 pm
by untitled
That link returns 404 now.
Could someone please share a working solution?

Re: [SOLVED] import module from filesystem

Posted: Fri Dec 13, 2019 12:06 pm
by Christian Walther
If you’re referring to the PewPew menu.py link, that has moved to https://github.com/pewpew-game/game-men ... er/main.py.