如何加载给定完整路径的Python模块?
请注意,文件可以位于文件系统中用户具有访问权限的任何位置。
另请参阅:如何导入以字符串形式命名的模块?
如何加载给定完整路径的Python模块?
请注意,文件可以位于文件系统中用户具有访问权限的任何位置。
另请参阅:如何导入以字符串形式命名的模块?
当前回答
对于Python 3.5+,使用(docs):
import importlib.util
import sys
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
sys.modules["module.name"] = foo
spec.loader.exec_module(foo)
foo.MyClass()
对于Python 3.3和3.4,请使用:
from importlib.machinery import SourceFileLoader
foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()
(尽管Python 3.4中已弃用此选项。)
对于Python 2,请使用:
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
编译后的Python文件和DLL有等效的方便函数。
另请参见http://bugs.python.org/issue21436.
其他回答
有一个包专门针对这一点:
from thesmuggler import smuggle
# À la `import weapons`
weapons = smuggle('weapons.py')
# À la `from contraband import drugs, alcohol`
drugs, alcohol = smuggle('drugs', 'alcohol', source='contraband.py')
# À la `from contraband import drugs as dope, alcohol as booze`
dope, booze = smuggle('drugs', 'alcohol', source='contraband.py')
它在Python版本(Jython和PyPy也是)中进行了测试,但根据项目的大小,它可能会被过度使用。
你的意思是装货还是进口?
您可以操作sys.path列表,指定模块的路径,然后导入模块。例如,给定位于以下位置的模块:
/foo/bar.py
你可以这样做:
import sys
sys.path[0:0] = ['/foo'] # Puts the /foo directory at the start of your path
import bar
如果我们在同一个项目中有脚本,但在不同的目录方式中,我们可以通过以下方法解决这个问题。
在这种情况下,utils.py位于src/main/util中/
import sys
sys.path.append('./')
import src.main.util.utils
#or
from src.main.util.utils import json_converter # json_converter is example method
向sys.path添加路径(与使用imp相比)的优点是,当从单个包导入多个模块时,可以简化操作。例如:
import sys
# the mock-0.3.1 dir contains testcase.py, testutils.py & mock.py
sys.path.append('/foo/bar/mock-0.3.1')
from testcase import TestCase
from testutils import RunTests
from mock import Mock, sentinel, patch
要导入模块,需要将其目录临时或永久添加到环境变量中。
暂时
import sys
sys.path.append("/path/to/my/modules/")
import my_module
永久地
在Linux中将以下行添加到.bashrc(或替代)文件中以及终端中的exccute source~/.bashrc(或替代):
export PYTHONPATH="${PYTHONPATH}:/path/to/my/modules/"
信贷/来源:saarrrr,另一个Stack Exchange问题