我花了一些时间研究这个问题,但我脑子里想不出这个问题。
我在它自己的目录home/program/core/main.py中运行一个程序
在main.py中,我尝试导入一个名为my_module.py的模块,该模块位于另一个目录中,例如home/程序模块/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一切都很好。但这并不理想,因为它现在取决于程序必须存在于家庭/程序之下这一事实。
发布于 2017-11-13 05:27:26
这是因为modules不是一个有效的python包,可能是因为它不包含任何__init__.py文件(如果不用__init__.py标记目录,就不能遍历带有import的目录)
因此,要么添加一个空的__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?
发布于 2018-05-24 12:18:16
虽然答案可以找到here,但为了方便和完整,这里有一个快速的解决方案:
import importlib
dirname, basename = os.path.split(pyfilepath) # pyfilepath: /my/path/mymodule.py
sys.path.append(dirname) # only directories should be added to PYTHONPATH
module_name = os.path.splitext(basename)[0] # /my/path/mymodule.py --> mymodule
module = importlib.import_module(module_name) # name space of defined module (otherwise we would literally look for "module_name")现在可以直接使用导入模块的命名空间,如下所示:
a = module.myvar
b = module.myfunc(a)https://stackoverflow.com/questions/47257548
复制相似问题