2014-01-29 68 views
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職位的,但是這似乎有點小題大做了我。

回答

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包。

+0

作品完美! – Brett