I have a folder with a few python files:
modules
|--> __init__.py
|--> car.py
|--> plane.py
|--> ship.py
|--> etc...
Each of this files consists on this:
car.py
NAME = "car_name"
def mainloop(*args):
...
return whatever
plane.py
NAME = "some_different_name"
def mainloop(*args):
...
return whatever
and so on...
I want to import them dynamically from my parent dir as a dict like this:
from modules import modules
print(modules)
{
"car_name": <function mainloop at ...>,
"some_different_name": <function mainloop at ...>,
etc..
}
I don't know how many files will be on the folder or the filenames. How can I do it?
modules.py
:
import os, importlib
fs = [f for f in os.listdir('.') if f.endswith('.py')]
modules = {m.NAME: m.mainloop for m in map(importlib.import_module, fs)
if hasattr(m, 'mainloop')}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.