从另一个目录导入 [英] Importing from another directory
问题描述
我正在使用以下文件夹体系结构构建我的Python应用程序(大致遵循大纲此处):
I am structuring my Python application with the following folder architecture (roughly following the outline 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.py
和 myapp_common2.py
中的函数.
This is ideal file/folder hierarchy for me, however, I am confused on how to reference modules from outside folders. For instance, myapp_service1_start.py
needs to reference function in myapp_common1.py
and myapp_common2.py
.
我知道我需要以某种方式添加对系统 path
或 pythonpath
的引用,但是我不确定在代码中执行此操作的最佳方法.或者更确切地说,我什至会在代码中执行此操作.
I know I need to somehow add reference to the system path
or pythonpath
, but I'm not sure the best way to do this in code. Or rather where I would even do this in code.
我该怎么做?
我已经看过很多关于通过 pip
创建要安装的完整Python包的文章,但这对我来说似乎太过分了.
I've seen a lot of posts about creating a full Python package to be installed via pip
, but this seems like overkill to me.
推荐答案
一种方法是使每个 myapp_service * _start.py
文件将 myapp/
目录添加到 sys.path
.
One way is to make each of your myapp_service*_start.py
files add myapp/
directory to sys.path
.
例如,将名为 import_me.py
的文件拖放到 myapp_service1/
中,该文件的代码将向上"目录(相对于导入文件)附加到sys.path
:
For example, drop a file called import_me.py
into myapp_service1/
with code that appends the "one up" directory (relative to importing file) to 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
中,您可以执行以下操作:
Then, in your myapp_service1_start.py
you can do something like:
import import_me
from common import myapp_common1
from common import myapp_common2
当然,请确保通过将(可能为空的) __ init __.py
文件放入Python包中来使 common
目录成为Python软件包.
Of course, be sure to make common
directory a Python package by dropping a (possibly empty) __init__.py
file into it.
这篇关于从另一个目录导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!