所以在一个foo文件中,我正在导入模块:
import lib.helper_functions
import lib.config
在helper_functions.py中,我有:
import config
当我运行foo的主函数时,我得到了一个
编辑:这是我的文件结构
foo.py
lib/
config.py
helper_functions.py
在helper函数中导入配置时出错
Traceback (most recent call last):
File "C:\Python33\foo.py", line 1, in <module>
import lib.helper_functions
File "C:\Python33\lib\helper_functions.py", line 1, in <module>
import config
ImportError: No module named 'config'
所以:当我运行foo.py时,解释器抱怨helper_函数的import语句。但是当我运行helper_函数的main时,没有出现这样的错误。
在python中,每个模块都有自己的名称空间。当导入另一个模块时,实际上只导入其名称。
名称“config”存在于模块helper_函数中,因为您在那里导入了它。在foo中导入helper_函数只会将名称“helper_function”带入foo的名称空间,而不会引入其他名称空间。
实际上,您可以在当前导入中引用foo.py中的“config”名称,方法如下:
但在python中,最好是显式的,而不是隐式的。因此在foo.py中导入配置将是最好的方法。
您需要使用绝对导入导入
config
。使用:或使用:
Python 3只支持绝对导入;语句}。
import config
只导入顶级模块^{您需要使用绝对导入导入
config
。使用:或使用:
Python 3只支持绝对导入;语句
import config
只导入顶级的模块config
。相关问题 更多 >
编程相关推荐