如何加载给定完整路径的Python模块?
请注意,文件可以位于文件系统中用户具有访问权限的任何位置。
另请参阅:如何导入以字符串形式命名的模块?
如何加载给定完整路径的Python模块?
请注意,文件可以位于文件系统中用户具有访问权限的任何位置。
另请参阅:如何导入以字符串形式命名的模块?
当前回答
我对@SebastianRittau的精彩回答(我认为Python>3.4)做了一个稍微修改的版本,它允许您使用spec_from_loader而不是spec_from_file_location加载具有任何扩展名的文件作为模块:
from importlib.util import spec_from_loader, module_from_spec
from importlib.machinery import SourceFileLoader
spec = spec_from_loader("module.name", SourceFileLoader("module.name", "/path/to/file.py"))
mod = module_from_spec(spec)
spec.loader.exec_module(mod)
在显式SourceFileLoader中编码路径的优点是,机器不会试图从扩展名中找出文件的类型。这意味着您可以使用此方法加载类似.txt文件的文件,但如果不指定加载器,则无法使用spec_from_file_location加载,因为.txt不在importlib.machinery.SOURCE_SUFFIX中。
我已经在此基础上放置了一个实现,@SamGrondahl对我的实用程序库haggis进行了有用的修改。该函数名为hagis.load.load_module。它添加了一些巧妙的技巧,例如在加载模块时将变量注入模块命名空间的能力。
其他回答
在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 *
创建Python模块test.py:
import sys
sys.path.append("<project-path>/lib/")
from tes1 import Client1
from tes2 import Client2
import tes3
创建Python模块test_check.py:
from test import Client1
from test import Client2
from test import test3
我们可以从模块导入导入的模块。
下面是一些适用于所有Python版本的代码,从2.7-3.5到其他版本。
config_file = "/tmp/config.py"
with open(config_file) as f:
code = compile(f.read(), config_file, 'exec')
exec(code, globals(), locals())
我测试了它。它可能很难看,但到目前为止,它是唯一一个适用于所有版本的。
要导入模块,需要将其目录临时或永久添加到环境变量中。
暂时
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问题
向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