Import all .py files in a folder #15741
Replies: 4 comments
-
run_test_module.py: from test_module import *
snapshot = globals().copy().items()
for key, value in snapshot:
print(f"{key:<10} => {value}") test_module/init.py: from test_module.a import value
__all__ = ("value",) test_module/a.py: value = 42 Run with python3:
Running with micropython (unix-port):
Running with micropython (esp32S3):
On the ESP32S3 I imported run_test_module, which then executes the code in run_test_module. |
Beta Was this translation helpful? Give feedback.
-
$ tree .
.
├── pkga
│ └── pkgb
│ ├── __init__.py
│ ├── M1.py
│ └── pkgc
│ ├── __init__.py
│ └── M2.py
└── test.py
3 directories, 5 files "pkga/pkgb/__init__.py" M1=__import__("M1", None, None, True, 1)
globals()["add"]=M1.add
globals()["prod"]=M1.prod "pkga/pkgb/M1.py" def add(a,b):
return a+b
def prod(a,b):
return a*b "pkga/pkgb/pkgc/__init__.py" M2=__import__("M2", None, None, True, 1)
globals()["minus"]=M2.minus
globals()["div"]=M2.div "pkga/pkgb/pkgc/M2.py" def minus(n,m):
return n-m
def div(n,m):
return n/m "test.py" import sys
print(sys.implementation)
from pkga.pkgb import *
from pkga.pkgb.pkgc import *
print('add(2,3) =', add(2,3))
print('prod(2,3) =', prod(2,3))
print('minus(5,3) =', minus(5,3))
print('div(5,3) =', div(5,3)) Run the test: $ mpremote mount . exec "import test"
Local directory . is mounted at /remote
(name='micropython', version=(1, 24, 0, 'preview'), _machine='WaveShare Pico Zero with RP2040', _mpy=4870)
add(2,3) = 5
prod(2,3) = 6
minus(5,3) = 2
div(5,3) = 1.666667 |
Beta Was this translation helpful? Give feedback.
-
I think all points are being missed. I have the following folder structure: /-- What I want to do is from a script in the root load whatever libraries are in the /lib folder without having to specify the individual library in the directory. THis is not possible in micropython as glob is not a valid module. Any ideas? |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
Question.... From https://docs.python.org/3/tutorial/modules.html I know that I can create an init.py in a folder path /foldera/folderb and define a variable all within which I define all modules that can be imported when executing:
from foldera.folderb import *
This does not appear to work in micropython 1.23.0 on a pico_w. is there another way (without explicitly importing each py file) to load all .py files in a folder?
Beta Was this translation helpful? Give feedback.
All reactions