我有一个 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