【发布时间】:2011-10-01 16:32:00
【问题描述】:
这是import python modules with the same name 的后续问题,但由于两者有些无关,最好提出一个新问题:
我有几个python项目,它们都有一个conf包:
/some_folder/project_1/
conf/
__init__.py
some_source_file.py
/another_folder/project_2/
conf/
__init__.py
another_source_file.py
对于每个项目,我在 site-packages 文件夹中创建了一个 .pth 文件,其中包含以下内容:
.../site-packages/project_1.pth:
import sys; sys.path.append('/some_folder/project_1/')
.../site-packages/project_2.pth:
import sys; sys.path.append('/another_folder/project_2/')
现在,访问 conf 模块适用于 /some_folder/project_1/:
import conf.some_source_file
但不适用于 /another_folder/project_2/:
import conf.another_source_file
AttributeError: 'module' object has no attribute 'another_source_file'
这可能是由于 python 只搜索 sys.path 中任何文件夹下的第一个 conf 路径。
因此,我将 project_1 和 project_2 转换为 python 包并在其中添加了一个符号链接,因此我可以以完全限定的方式访问这两个 conf 包:
/some_folder/project_1/
__init__.py
project_1 <-- symlink to .
conf/
__init__.py
some_source_file.py
/another_folder/project_2/
__init__.py
project_2 <-- symlink to .
conf/
__init__.py
another_source_file.py
在一个普通的 python 脚本中,我现在可以从两个 conf 包中导入模块:
import project_1.conf.some_source_file
import project_2.conf.another_source_file
但是,当我尝试使用 mod_wsgi Apache 模块在 WSGI 应用程序中执行相同操作时,第二个项目的导入失败。具体来说,wsgi“启动文件”(即在我的虚拟服务器的 Apache 配置文件中的 WSGIScriptAlias 语句中引用的带有 wsgi 后缀的文件)成功地在 /another_folder/project_2/ 中导入了一个模块,该模块又导入了 project_2/conf/another_source_file .py.
第二次导入失败,尽管 /another_folder/project_2/ 在 sys.path 中。 WSGI 应用程序正在守护程序模式下运行。
我怎样才能得到这个排序?
【问题讨论】: