特定于应用程序的PYTHONPATH
我有一个拥有包继承权的申请。有相当多的模块引用了包继承权中更高级别的其他模块。如下例所示,我可以使用相对进口来解决这个问题。但是,直接运行模块进行测试失败,出现特定于应用程序的PYTHONPATH,python,pythonpath,sys.path,Python,Pythonpath,Sys.path,我有一个拥有包继承权的申请。有相当多的模块引用了包继承权中更高级别的其他模块。如下例所示,我可以使用相对进口来解决这个问题。但是,直接运行模块进行测试失败,出现尝试在非包中进行相对导入的异常 有没有更好的方法来组织我的应用程序或导入语句,以便模块可以单独执行以进行测试,也可以从其他模块导入 例子 base.py class Base(object): def hello(self): print 'Um, wot?' from ..base import Base
尝试在非包中进行相对导入的异常
有没有更好的方法来组织我的应用程序或导入语句,以便模块可以单独执行以进行测试,也可以从其他模块导入
例子
base.py
class Base(object):
def hello(self):
print 'Um, wot?'
from ..base import Base # references the parent package correctly,
# but fails when this module is executed individually
class Child(Base):
def hello(self):
print 'Hello, world!'
if __name__ == '__main__':
import unittest
# ... unit test code ...
from spam.morespam.child import Child
print Child().hello()
child.py
class Base(object):
def hello(self):
print 'Um, wot?'
from ..base import Base # references the parent package correctly,
# but fails when this module is executed individually
class Child(Base):
def hello(self):
print 'Hello, world!'
if __name__ == '__main__':
import unittest
# ... unit test code ...
from spam.morespam.child import Child
print Child().hello()
user.py
class Base(object):
def hello(self):
print 'Um, wot?'
from ..base import Base # references the parent package correctly,
# but fails when this module is executed individually
class Child(Base):
def hello(self):
print 'Hello, world!'
if __name__ == '__main__':
import unittest
# ... unit test code ...
from spam.morespam.child import Child
print Child().hello()
现有解决方案
我发现我可以将以下标题添加到需要引用层次结构中较高模块的模块顶部:
if __name__ == '__main__':
import sys, os
sys.path.append(os.path.abspath(os.path.join(sys.path[0], '..')))
缺点是我需要在所有地方添加此代码,而且它不是恒定的:“…”
相对路径根据包在层次结构中的深度而变化
其他可能的解决方案。。。
我可以用我的应用程序根创建一个.pth文件。不幸的是,这必须添加到Python安装的site packages文件夹中,因此它不是非常特定于应用程序的
我可以,并使我的所有模块从根目录引用包。不过,这通过简单地调用python.exe whatever.py
,消除了运行脚本的简单性
我可以编写某种模块,在导入时,在我的应用程序的根文件夹中查找标记文件。然后,这个通用模块可以安装到我的本地Python安装中,并由我的应用程序中的每个模块导入,从而保证根目录在PYTHONPATH中,而不管我正在执行哪个模块
您需要将\uuuu init\uuuu.py
作为空文件添加到要从中进行导入的文件夹中。这样做将导致python将目录视为包,从而允许您在导入语句中使用它们:
\spam
\morespam
__init__.py
child.py
__init__.py
base.py
\eggs
__init__.py
user.py
完成此操作并将PYTHONPATH建立到此目录的基础后,您可以执行导入操作:
base.py:
from morespam.child import Child
from ..eggs import user
虽然只需要存在一个\uuuuu init\uuuuuuuuu.py
文件,但您也可以将该文件中的变量\uuuuuuu ALL\uuuuuuuuuuuuuu
定义为该目录中的模块列表,如果脚本试图使用导入*
我用PyCharm解决了这个问题,它会在每次运行我的应用程序时自动将我的源根添加到PYTHONPATH。据我所知,PyCharm基本上为我提供了选项2。我在示例代码中遗漏了\uu init\uuuuuuupy.py
文件,因为它们与我的问题并不相关。我的软件包设置良好,外部模块完全可用。我的问题是,我想知道如何在其中一个子包中运行脚本,以便它可以导入包层次结构中更高层次的模块,而无需将我的应用程序根添加到PYTHONPATH
。