我有一个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 :(得分:5)
在Python中,要求宽恕通常比允许(EAFP)更容易。当您遇到ValueError
,continue
到下一次迭代时:
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
答案 1 :(得分:4)
抓住转换失败时发生的ValueError
异常:
try:
temp_C = float(temp)
except ValueError:
temp_C = 0.0