Django绝对进口

时间:2014-05-21 11:04:49

标签: python django import module package

假设有一个名为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'>

2 个答案:

答案 0 :(得分:2)

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进程/实例(在本例中为交互式会话),后续进程将以原始路径启动。

无需修改路径的解决方案

如果您不能或不想修改sys.path,可以使用imp模块手动导入模块:

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)

答案 1 :(得分:1)

试试这个,没有硬代码路径

import os
import sys
PROJECT_DIR = os.path.dirname(__file__) 
# make sure the path is right, it depends on where you put the file is

# If PROJECT_DIR in sys.path, remove it and append to the end.
syspath = sys.path
syspath_set = set(syspath)
syspath_set.discard(PROJECT_DIR)
sys.path = list(syspath_set)

sys.path.append(PROJECT_DIR)

# Then try
import foobar

# At last, change it back, prevent other import mistakes
sys.path = syspath