Ayu*_*ush 4 python python-importlib python-3.7
我有这样的目录结构:
__init__.py
test.py
dir1/
__init__.py
dir2
__init__.py
myfile.py
Run Code Online (Sandbox Code Playgroud)
dir2 中可能还有更多 py 文件。所以我想在运行时导入它们并加载这些文件中定义的所有类。
测试.py:
import inspect
import importlib
module = importlib.import_module('dir1/dir2/myfile.py')
for name, obj in inspect.getmembers(module):
if inspect.isclass(module):
print(obj.id) # id is defined in all the classes
Run Code Online (Sandbox Code Playgroud)
这在执行 import_module 时给了我错误:
ModuleNotFoundError:没有名为“dir1/dir2/myfile”的模块
我尝试将 dir1/dir2 路径附加到 sys.path,然后导入 myfile.py,但这也不起作用。类似的代码也可以工作,将 myfile.py 放置在与 test.py 相同的级别。
Python版本:3.7
为了清楚起见,再次重申:
import_module()只接受带点的模块路径,不接受文件名。例如,importlib.import_module('dir1.dir2.myfile')