2013-07-29 45 views
0

我使用的是Python腳本的三個文件的內容傳輸到不同的三個文件。原始文件是來自我連接到運行raspian的RPI的三個溫度計的數據。所有腳本應該做的就是獲取文件的內容並移動它們,以便我可以讓另一個程序(ComScript)讀取並解析它們。Python的失敗文件處理凍結

我的問題是,如果一個或多個溫度計的腳本開始前被斷開,它凍結。如果腳本運行時斷開溫度計,它不會凍結。

下面是代碼

import time 
a = 1 
while a == 1: 
try: 
    tfile = open("/sys/bus/w1/devices/28-000004d2ca5e/w1_slave") 
    text = tfile.read() 
    tfile.close() 
    temperature = text 



    tfile2 = open("/sys/bus/w1/devices/28-000004d2fb20/w1_slave") 
    text2 = tfile2.read() 
    tfile2.close() 
    temperature2 = text2 


    tfile3 = open("/sys/bus/w1/devices/28-000004d30568/w1_slave") 
    text3 = tfile3.read() 
    tfile3.close() 
    temperature3 = text3 



    textfile = open("/home/pi/ComScriptPi/profiles/Temperature_parse/w1_slave1", "w ") 
    textfile2 = open("/home/pi/ComScriptPi/profiles/Temperature_parse/w1_slave2", "w ") 
    textfile3 = open("/home/pi/ComScriptPi/profiles/Temperature_parse/w1_slave3", "w ") 
    temperature = str(temperature) 
    temperature2 = str(temperature2) 
    temperature3 = str(temperature3) 
    textfile.write(temperature) 
    textfile2.write(temperature2) 
    textfile3.write(temperature3) 
    textfile.close() 
    textfile2.close() 
    textfile3.close() 
    print temperature 
    print temperature2 
    print temperature3 
    time.sleep(3) 

except: 
    pass 

我加入了異常傳遞,因爲我需要它來維持運行,即使它得到壞值。當其中一個溫度計斷開時,python試圖讀取的文件是空白的,但仍然存在。

+1

你是否期待'a'在某個點上不等於1? – roippi

回答

4

除去毯子。

您的腳本是而不是凍結,但是您得到的任何錯誤都會在無限循環中被忽略。因爲你用毯子except:你抓住所有異常,包括鍵盤中斷異常KeyboardInterrupt

至少,日誌例外,只有Exception趕上:

except Exception: 
    import logging 
    logging.exception('Oops: error occurred') 

KeyboardInterruptBaseException,不Exception子類,並不會受此除了處理程序捕獲。

看看在shutil module複製文件,你做了太多的工作:

import time 
import shutil 
import os.path 

paths = ('28-000004d2ca5e', '28-000004d2fb20', '28-000004d30568') 

while True: 
    for i, name in enumerate(paths, 1): 
     src = os.path.join('/sys/bus/w1/devices', name, 'w1_slave') 
     dst = '/home/pi/ComScriptPi/profiles/Temperature_parse/w1_slave{}'.format(i) 
     try: 
      shutil.copyfile(src, dst) 
     except EnvironmentError: 
      import logging 
      logging.exception('Oops: error occurred') 

    time.sleep(3) 

處理文件應該只不斷提高EnvironmentError或它的子類,有沒有需要捕獲一切這裏。

+0

謝謝,我試試這個,但爲什麼python會停止打印數據,我會告訴它在腳本中,以及爲什麼電腦開始工作真的很難。 – user2631867

+0

無限循環做到這一點... –

+0

@ user2631867:那是因爲你有一個無限循環。即使'time.sleep(3)'調用也被跳過,因此循環會使CPU保持忙碌狀態。 –

0

開不插電裝置的最有可能阻止,因爲如果該設備不存在設備驅動程序將無法打開。

你需要使用os.open這是Unix系統調用「打開」,並指定標誌O_NONBLOCK並檢查返回碼的等價物。然後您可以使用os.fdopen將os.open的返回值轉換爲普通的Python文件對象。

+1

這不會導致CPU進入超速模式並啓動風扇。看到我的答案下面的評論;代碼處於無限循環中。 –

+0

不,它不會。但這也是一個可能的因素。 –