假设有一个名为 foobar
的系统范围模块,以及一个名为 foobar
的 Django 应用程序我也无法编辑它们,因为它们是外部项目。
现在,我想使用系统 foobar 模块,而不是应用程序,但它不起作用:
$ python --version
Python 2.7.3
$ ./manage.py --version
1.3.1
$ ./manage.py shell
>>> import foobar
>>> print (foobar)
<module 'foobar' from '/path/to/myproject/foobar/__init__.pyc'>
我该怎么办?我想我会有 <module 'foobar' from '/usr/lib/python2.7/dist-packages/foobar/__init__.pyc'>
相反。
最佳答案
Python 在环境变量 PYTHONPATH
中定义的位置查找包。您可以在 Python 中轻松修改它:
https://docs.python.org/2/install/index.html#modifying-python-s-search-path
您需要更改 sys.path
,以便包含系统 foobar 模块的目录位于应用程序目录之前。
假设您的 sys.path
如下所示:
>>> import sys
>>> sys.path
['', '/usr/local/lib/python2.7/site-packages']
和 foobar
既位于当前工作目录(用 ''
表示),又位于系统 site-packages
目录中,您希望让系统 foobar
更靠近列表的前面:
>>> sys.path.insert(0, '/usr/local/lib/python2.7/site-packages/foobar')
>>> sys.path
['/usr/local/lib/python2.7/site-packages/foobar',
'', '/usr/local/lib/python2.7/site-packages']
请注意,对路径的更改仅适用于正在运行的 Python 进程/实例(在本例中为交互式 session ),后续进程将使用原始路径启动。
不修改路径的解决方案
如果您不能或不想修改 sys.path,您可以使用 imp
module 手动导入模块:
import imp
name = 'foobar'
path = '/usr/local/lib/python2.7/site-packages/foobar'
fp, pathname, description = imp.find_module(name, path)
try:
imp.load_module(name, fp, pathname, description)
finally:
# Make sure the file pointer was closed:
if fp:
fp.close()
仅临时修改路径的解决方案
此解决方案不需要提前知道系统 foobar
包位于何处,只需知道当前目录中不在的包即可:
import imp
import sys
# Temporarily remove the current working directory from the path:
cwd = sys.path.pop(0)
# Now we can import the system `foobar`:
import foobar
# Put the current working directory back where it belongs:
sys.path.insert(0, cwd)
关于python - Django 绝对导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23781386/