我有一個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
這會將非浮點值轉換爲「0.0」(它看起來像)。我希望能夠跳過這個錯誤,而不是像以前那樣報告0.0。 – user1813343
啊。如果你想完全跳過它們,把'continue'放在你的except子句中。編輯答案來做到這一點。 –
非常感謝,這正是我一直在尋找的! – user1813343