#main program
while True:
ReadValue = Func03Modbus(1,70,40);#slave,start,number of registers
x3 = struct.pack('>HH',abs(ReadValue[3]),abs(ReadValue[2]))
pressure = struct.unpack('>f', x3)
print pressure[0]
c3 = struct.pack('>HH',abs(ReadValue[5]),abs(ReadValue[4]))
purity = struct.unpack('>f', c3)
print purity[0]
hrs = int(ReadValue[30])
mins= int(ReadValue[31])
timein =float(str(ReadValue[30])+"."+str(ReadValue[31]))
print timein
r=requests.get("http://api.thingspeak.com/update api_key=5RMT************&field4="+str(pressure[0])+"&field5="+str(purity[0])+"&field1="+str(ReadValue[i])+"&field2="+str(mins)+"&field3="+str(timein)))
print str(ReadValue[30])
time.sleep(15)
运行上述程序时,它会停止运行并返回以下错误:
回溯(最近一次呼叫最后一次):文件" /home/pi/v1.py" ;,第123行, 在 x3 = struct.pack('> HH',abs(ReadValue [3]),abs(ReadValue [2])); IndexError:元组索引超出范围
我希望我的程序即使在返回错误时也能连续运行。我想跳过错误并继续运行程序。我怎样才能做到这一点 ?
答案 0 :(得分:2)
理论上,您可以将代码包装在异常处理程序中,如:
while True:
try:
what you want to do
except Exception as e:
print("Something bad happened:", e)
finally:
# reset device here
time.sleep(15)
但如果您与硬件进行互动,这似乎是一个非常糟糕的主意,因为您无法确定您将其留在哪个州。理想情况下,您想要确保你在每个周期都正确地重置设备(或重新连接?取决于你所说的话)。
或者,如果您想明确验证您获得的值是否可用,您可以执行以下操作:
ReadValue = Func03Modbus(1,70,40);#slave,start,number of registers
if len(ReadValue) < 32:
print("Got incomplete result")
time.sleep(15)
continue
语言参考/教程提供了有关处理错误的更多信息:https://docs.python.org/3/tutorial/errors.html
答案 1 :(得分:0)
为了在发生此类错误时继续,只需将您希望忽略的部分放在适当的try: ... except ...
while True:
try:
<body of work>
except IndexError:
<you might want to log the error>
pass
在这种情况下,我们只会在IndexError
。