我花了一些时间研究这个,但我就是无法在脑海中解决这个问题。
我在它自己的目录 home/program/core/main.py 中运行一个程序
在 main.py 中,我尝试导入一个名为 my_module.py 的模块,该模块位于不同的目录中,比如 home/program/modules/my_module.py
在 main.py 中,这就是我附加到 sys.path 的方式,因此该程序可以在任何人的机器上运行(希望如此)。
import os.path
import sys
# This should give the path to home/program
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__), '..'))
# Which it does when checking with
print os.path.join(os.path.abspath(os.path.dirname(__file__), '..')
# So now sys.path knows the location of where modules directory is, it should work right?
import modules.my_module # <----RAISES ImportError WHY?
但是如果我只是这样做:
sys.path.append('home/program/modules')
import my_module
一切正常。但这并不理想,因为它现在取决于程序必须存在于 home/program 下这一事实。
请您参考如下方法:
那是因为 modules 不是一个有效的 python 包,可能是因为它不包含任何 __init__.py 文件(你不能使用 import 遍历目录而不用 __init__.py)
因此,要么添加一个空的 __init__.py 文件,要么只添加到 modules 的路径,这样您的第一个片段就等同于第二个片段:
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__), '..','modules'))
import my_module
请注意,您还可以使用高级导入功能通过提供完整路径来导入模块:How to import a module given the full path?
