简体   繁体   English

从另一个目录导入

[英]Importing from another directory

I am structuring my Python application with the following folder architecture (roughly following the outline here ): 我正在使用以下文件夹架构构建我的Python应用程序(大致遵循此处的大纲):

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

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 . 例如, myapp_service1_start.py需要引用myapp_common1.pymyapp_common2.py函数。

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. 我知道我需要以某种方式添加对系统pathpythonpath ,但我不确定在代码中执行此操作的最佳方法。 Or rather where I would even do this in code. 或者更确切地说,我甚至会在代码中执行此操作。

How can I do this? 我怎样才能做到这一点?

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. 我已经看到了很多有关创建一个完整的Python包通过将要安装的职位pip ,但这似乎有点小题大做了我。

One way is to make each of your myapp_service*_start.py files add myapp/ directory to sys.path . 一种方法是使每个myapp_service*_start.py文件将myapp/目录添加到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_me.pymyapp_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)

Then, in your myapp_service1_start.py you can do something like: 然后,在myapp_service1_start.py您可以执行以下操作:

import import_me
from common import myapp_common1
from common import myapp_common2

Of course, be sure to make common directory a Python package by dropping a (possibly empty) __init__.py file into it. 当然,一定要通过将一个(可能为空的) __init__.py文件放入其中来使common目录成为Python包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM