我希望将一组模块从子目录导入父目录中的单个主模块:
项目/
main.py
subdirectory/
__init__.py
timer.py
example.py
我可以要求任何一个.py文件,如下所示:
from subdirectory import timer.py
但是,如果我运行以下命令
from subdirectory import *
如果我尝试使用该子目录中的模块,则会出现以下错误:
File "My:\Path\Here\...", line 33, in main
t = timer.timer()
NameError: name 'timer' is not defined
我希望能够在一批中导入所有文件,因为我要导入几个模块。我已经在子目录中添加了一个空白的init.py文件。 有什么我遗漏的吗
必须在
__init__.py
中使用__all__
声明模块名称:__init__.py
:这种行为是documented:
如果只想使导入工作,请添加具有以下内容的
subdirectory/__init__.py
:但是,如果您想对任意数量的(旧的和新的)模块执行此操作,我认为this answer可能就是您想要的:
您可以从以下结构开始:
然后从
main.py
导入subdirectory
中的所有内容:然后将以下内容添加到
subdirectory/__init__.py
模块:为了完整起见
subdirectory/timer.py
模块:进口是这样的
尝试将
__init__.py
添加到子目录。 它现在看起来像:项目/
如果这不起作用: 在
main.py
中添加相关问题 更多 >
编程相关推荐