我有一个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
Run Code Online (Sandbox Code Playgroud)
目前的代码是:
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
Run Code Online (Sandbox Code Playgroud)
在Python中,要求宽恕通常比允许(EAFP)更容易.遇到a时ValueError
,continue
到下一次迭代:
try:
temp_C = float(temp_C)
except ValueError:
continue # skips to next iteration
Run Code Online (Sandbox Code Playgroud)
或者更紧凑(巩固你的大部分功能):
try:
temp_C = float(sensor_reading.split(' ')[4].rstrip('C'))
except (ValueError, IndexError):
continue
Run Code Online (Sandbox Code Playgroud)