2015-08-29 71 views
0

我有一個讀取溫度傳感器文件並將其寫入數據庫的功能。但是,傳感器不會一直連接,因爲它們是便攜式的。可能發生的情況是,在腳本中間,傳感器斷開,導致該功能停止並等待傳感器連接回去。即使沒有傳感器,我也希望該功能可以運行。Python - 超時 - 跳過功能或循環

由於功能是循環檢查不同的傳感器,我正在考慮跳過循環或其中的功能。

我從這裏找到類似的東西:Timeout function if it takes too long to finish 除了一個想法,它完美的工作,它打破了功能,並停止腳本....我需要它再次運行。感謝您的幫助。

下面是代碼:

def read_all(): 

    base_dir = '/sys/bus/w1/devices/' 
    sensors=['28-000006dcc43f', '28-000006de2bd7', '28-000006dc7ea9', '28-000006dd9d1f','28-000006de2bd8'] 

    for sensor in sensors: 
     os.system('modprobe w1-gpio') 
     os.system('modprobe w1-therm') 

     device_folders = glob.glob(base_dir + sensor) 
     if len (device_folders) == 0: 
       continue 
     device_folder = device_folders[0] 
     if not os.path.isdir(base_dir): 
       continue 
     device_file = device_folder + '/w1_slave' 
     if not os.path.isfile(device_file): 
       continue 
     @timeout(5):  
     def read_temp_raw(): 
      catdata = subprocess.Popen(['cat',device_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
      out,err = catdata.communicate() 
      out_decode = out.decode('utf-8') 
      lines = out_decode.split('\n') 
      return lines 
     def read_temp(): 
      lines = read_temp_raw() 
      while lines[0].strip()[-3:] != 'YES': 
       time.sleep(0.2) 
       lines = read_temp_raw() 
      equals_pos = lines[1].find('t=') 
      if equals_pos != -1: 
       temp_string = lines[1][equals_pos+2:] 
       temp_c = float(temp_string)/1000.0 
       temp_f = temp_c * 9.0/5.0 + 32.0 
       return temp_c 

     temp = read_temp() 

     db=MySQLdb.connect("localhost","root","password","temps") 
     curs=db.cursor() 
     loggit= "insert into log1 values (current_date(), now(), %s, %s)" 
     curs.execute (loggit, (temp, sensor)) 
     db.commit()   

     print temp, sensor 
     #print(read_temp()) 

while True: 
    read_all() 
    time.sleep(1) 
+0

這是一個後續問題http://stackoverflow.com/questions/32269775/python-raspberry-pi-if-path-doesnt-exist-skip-the-loop –

回答

0

你發送一個信號,你的進程,這是不是你的腳本抓獲。

嘗試捕捉並處理信號。

def alarm_received(signo, stack): 
    print "signal caught {}".format(signo) 

signal.signal(signal.SIGALRM, alarm_received) 
+0

你可以請一點點更具體關於我應該在哪裏插入? – Miroslav

+0

您可以在腳本中添加一些方法。請閱讀有關signal.handling的更多信息https://docs.python.org/2/library/signal.html –