2014-05-10 46 views
0

我有一個web應用程序和連接到我的服務器的移動應用程序。在我的服務器中,我有一個模塊(md.py),它使用另一個模塊(config.py)從本地XML文件讀取數據。IOError:[Errno 2]偶爾沒有這樣的文件或目錄

當我發送一個請求到config.py(間接)從我的應用程序的數據一切工作正常。當我從同一臺機器上的md.py調用config.py時就會出現這個問題。

這是層級:

root/ 
    start.py 

    md/ 
    __init__.py 
    md.py 

    server/ 
    __init__.py 
    config.py 
    server.py 

    data/ 
     config.xml 

這是md.py

from server import config 

class Md: 

    def get_data(self):   
     conf = config.Config() # Errno 2 here 

這是config.py

import xml.etree.ElementTree as ET 

CONF_FILE = "data/config.xml" 

class Config: 

    def __init__(self): 
     self.file = ET.parse(CONF_FILE) 
     self.root = self.file.getroot() 

這就是我如何start.py

運行這些文件
def start(): 
    global server_p 

    server_p = subprocess.Popen('python ./server/server.py') 
    md = subprocess.Popen('python ./md/md.py') 

我能做些什麼來解決這個問題?

+0

嘗試使config.py文件運行ls命令,我認爲工作目錄可能不是它實際位於的目錄。 – Natecat

+0

有沒有一種方法可以動態獲取正確的路徑? –

回答

2

首次進口dirnamejoinos.path模塊config.py

from os.path import dirname, join 

然後換CONF_FILE到:的__file__爲一些代碼中定義的文件的絕對路徑

CONF_FILE = join(dirname(__file__), 'data', 'config.xml') 

思考,當時它被作爲一個模塊加載。 dirname將採用該路徑併爲您提供文件所在目錄的路徑,並且join將任意數量的參數串入新路徑中。

所以首先我們通過閱讀__file__得到{abs_path_to}root/server/config.py。然後dirname(__file__)讓我們到{abs_path_to}root/server。加入data,然後​​3210終於給我們{abs_path_to}root/server/data/config.xml

+0

我試圖做這樣的事情,並沒有成功,缺少'dirname(__ file __)'。謝謝您的幫助。 –

相關問題