如何加载给定完整路径的Python模块?
请注意,文件可以位于文件系统中用户具有访问权限的任何位置。
另请参阅:如何导入以字符串形式命名的模块?
如何加载给定完整路径的Python模块?
请注意,文件可以位于文件系统中用户具有访问权限的任何位置。
另请参阅:如何导入以字符串形式命名的模块?
当前回答
你的意思是装货还是进口?
您可以操作sys.path列表,指定模块的路径,然后导入模块。例如,给定位于以下位置的模块:
/foo/bar.py
你可以这样做:
import sys
sys.path[0:0] = ['/foo'] # Puts the /foo directory at the start of your path
import bar
其他回答
您也可以执行类似的操作,将配置文件所在的目录添加到Python加载路径中,然后进行正常导入,假设您事先知道文件的名称,在本例中为“config”。
凌乱,但它有效。
configfile = '~/config.py'
import os
import sys
sys.path.append(os.path.dirname(os.path.expanduser(configfile)))
import config
在Linux中,可以在Python脚本所在的目录中添加符号链接。
即。:
ln -s /absolute/path/to/module/module.py /absolute/path/to/script/module.py
Python解释器将创建/aabsolute/path/to/script/module.pyc,如果您更改/aabsolute/path/to-module/module.py的内容,Python解释器将对其进行更新。
然后在文件mypythonscript.py中包含以下内容:
from module import *
要导入模块,需要将其目录临时或永久添加到环境变量中。
暂时
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问题
对于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.
这应该行得通
path = os.path.join('./path/to/folder/with/py/files', '*.py')
for infile in glob.glob(path):
basename = os.path.basename(infile)
basename_without_extension = basename[:-3]
# http://docs.python.org/library/imp.html?highlight=imp#module-imp
imp.load_source(basename_without_extension, infile)