从另一个目录导入

3
我正在使用以下文件夹结构组织我的Python应用程序(大致按照这里的概述进行 here):
myapp:
    myapp_service1:
        myapp_service1_start.py
        ...
    myapp_service2:
        myapp_service2_start.py
        ...
    myapp_service3:
        myapp_service3_start.py
        ...
    common:
        myapp_common1.py
        myapp_common2.py
        myapp_common3.py
        ...
scripts:
    script1.py
    script2.py
    script3.py
    ...
tests:
    ...
docs:
    ...
LICENSE.txt
MANIFEST.in
README

这是我理想的文件/文件夹层次结构,但是我不知道如何引用来自其他文件夹的模块。例如,myapp_service1_start.py 需要引用 myapp_common1.pymyapp_common2.py 中的函数。

我知道我需要在系统的 pathpythonpath 中添加引用,但是我不确定在代码中最好的实现方式。或者我应该在代码的哪里进行操作。

我该怎么做?

我看到很多关于创建完整 Python 包以通过 pip 进行 安装 的帖子,但我认为这似乎有些过度了。

1个回答

2
一种方法是让你的每个myapp_service*_start.py文件将myapp/目录添加到sys.path中。
例如,将名为import_me.py的文件放入myapp_service1/中,并编写代码将“向上一级”目录(相对于导入文件)附加到sys.path中:
import os
import sys
import inspect
this_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
src_dir = os.path.join(this_dir, '..')
sys.path.insert(0, src_dir)

然后,在你的myapp_service1_start.py文件中,你可以这样做:
import import_me
from common import myapp_common1
from common import myapp_common2

当然,一定要通过在其中添加(可能为空的)__init__.py文件,使common目录成为Python包。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接