importlib 不适用于子目录中的文件
importlib not working for files in subdirectory
我有这样的目录结构:
__init__.py
test.py
dir1/
__init__.py
dir2
__init__.py
myfile.py
dir2 中可能有更多py 文件。所以我想在 运行 时间导入它们并加载这些文件中定义的所有 类。
test.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
这让我在做 import_module 时出错:
ModuleNotFoundError: No module named 'dir1/dir2/myfile'
我尝试将 dir1/dir2 路径附加到 sys.path,然后导入 myfile.py,这也不起作用。同样类似的代码工作是 myfile.py 被放置在与 test.py.
相同的水平
Python 版本:3.7
为了清楚起见再次重申:
import_module()
只接受带点的模块路径,不接受文件名。例如,importlib.import_module('dir1.dir2.myfile')
我有这样的目录结构:
__init__.py
test.py
dir1/
__init__.py
dir2
__init__.py
myfile.py
dir2 中可能有更多py 文件。所以我想在 运行 时间导入它们并加载这些文件中定义的所有 类。
test.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
这让我在做 import_module 时出错:
ModuleNotFoundError: No module named 'dir1/dir2/myfile'
我尝试将 dir1/dir2 路径附加到 sys.path,然后导入 myfile.py,这也不起作用。同样类似的代码工作是 myfile.py 被放置在与 test.py.
相同的水平Python 版本:3.7
为了清楚起见再次重申:
import_module()
只接受带点的模块路径,不接受文件名。例如,importlib.import_module('dir1.dir2.myfile')