2012-11-12 34 views
2

我有一個USB溫度記錄器,每30秒上傳到Cosm。我遇到的問題是每5分鐘運行命令時報告一個文本錯誤而不是數字。如何忽略非浮點值

因此,我試圖找出一種方法來讓它循環,直到它收到一個數字或者只是忽略文本並恢復腳本(否則它會退出一個錯誤)。

我非常不雅的解決辦法是要做到這一點:

# convert regular error message to number 
    if temp_C == "temporarily": # "temporarily" is used as it happens to be the 4th word in the error message 
      temp_C = 0.0 

當前代碼體是:

while True: 
    # read data from temper usb sensor 
    sensor_reading=commands.getoutput('pcsensor') 

    #extract single temperature reading from the sensor 

    data=sensor_reading.split(' ') #Split the string and define temperature 
    temp_only=str(data[4]) #knocks out celcius reading from line 
    temp=temp_only.rstrip('C') #Removes the character "C" from the string to allow for plotting 

    # calibrate temperature reading 
    temp_C = temp 

    # convert regular error message to number 
    if temp_C == "temporarily": 
      temp_C = 0.0 

    # convert value to float 
    temp_C = float(temp_C) 

    # check to see if non-float 
    check = isinstance(temp_C, float) 

    #write out 0.0 as a null value if non-float 
    if check == True: 
      temp_C = temp_C 
    else: 
      temp_C = 0.0 

回答

5

在Python中,它往往更容易請求原諒比許可(EAFP) 。當你遇到一個ValueErrorcontinue下一次迭代:

try: 
    temp_C = float(temp_C) 
except ValueError: 
    continue # skips to next iteration 

或者更緊湊(整合大部分的功能):

try: 
    temp_C = float(sensor_reading.split(' ')[4].rstrip('C')) 
except (ValueError, IndexError): 
    continue 
+0

這會將非浮點值轉換爲「0.0」(它看起來像)。我希望能夠跳過這個錯誤,而不是像以前那樣報告0.0。 – user1813343

+0

啊。如果你想完全跳過它們,把'continue'放在你的except子句中。編輯答案來做到這一點。 –

+0

非常感謝,這正是我一直在尋找的! – user1813343

4

正好趕上發生的ValueError異常,當轉換失敗:

try: 
    temp_C = float(temp) 
except ValueError: 
    temp_C = 0.0 
+0

謝謝,這是很多整理 - 但是,我希望避免用零替換它,只是跳過代碼運行(因爲我正在繪製這些值,所有時間看起來凌亂爲零)。 – user1813343

+1

您可以跳過上面顯示的值。另一種選擇是重新使用先前的測量。 –