Importing from another directory

懵懂的女人 提交于 2019-12-07 14:31:59

问题


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

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.

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.

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.


回答1:


One way is to make each of your myapp_service*_start.py files add myapp/ directory to 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)

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

Of course, be sure to make common directory a Python package by dropping a (possibly empty) __init__.py file into it.



来源:https://stackoverflow.com/questions/21437126/importing-from-another-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!