[英]Why can't Main Module see sub-module inside it?
我正在编辑以最小化为可重现的示例:
cal.py 的内容
import M1
M1.SM1.nice_hello.hello()
目录结构:
M1/
├── __init__.py
└── SM1
├── __init__.py
└── nice_hello.py
SM1/nice_hello.py 的内容:
def hello():
print(f'Hello my friend!!!')
所有其他文件( init .py 文件)都是空的。
要运行 cal.py:
export PYTHONPATH=/PATH/TO/M1 ; python cal.py
但这给了我以下错误:
Traceback (most recent call last):
File "cal.py", line 3, in <module>
M1.SM1.nice_hello.hello()
AttributeError: module 'M1' has no attribute 'SM1'
如果您导入整个模块名称,即在文件cal.py
中,它应该可以工作
import M1.SM1.nice_hello
M1.SM1.nice_hello.hello()
子模块不会以递归方式导入,如果您希望这样做,您可以执行以下操作:-
A)在 M1 模块中创建init .py 文件(我想你已经有了)
B)在您的init .py 文件中有以下代码:-
import importlib
import pkgutil
def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
"""
if isinstance(package, str):
package = importlib.import_module(package)
results = {}
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
full_name = package.__name__ + '.' + name
results[full_name] = importlib.import_module(full_name)
if recursive and is_pkg:
results.update(import_submodules(full_name))
return results
这将帮助您导入 package ( M1 ) 中的所有子模块
现在在您的 cal.py 中执行以下操作:-
import M1
M1.import_submodules(M1)
def hello():
print(f'Hello my friend!!!')
希望这能解决您的问题,并可能指导您如何在 python 中递归地导入模块
参考:- 如何导入所有子模块?
如果需要进一步澄清,请在评论中联系。 很乐意提供帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.