我正在尝试从四个使用HTTP连接监视流体槽的Web服务器读取状态。这些服务器中的一个或多个不存在并不罕见,但没关系,我只想记录超时错误并继续其他服务器并获取其状态。 当它发生时,我无法弄清楚如何处理超时? 并始终对此代码的任何其他批评开放......我是Python的新手。
** Fluid tank Reader
import http.client
activeTanks = 4;
myTanks=[100,100,100,100]
for tank in range(0,activeTanks):
tankAddress = ("192.168.1.4"+str(tank))
conn = http.client.HTTPConnection(tankAddress, timeout=1)
## How do I handle the exception and finish the For Loop?
conn.request("GET", "/Switch=Read")
r1 = conn.getresponse()
conn.close()
myTanks[tank] = int(r1.read().decode('ASCII').split("...")[1])
print(myTanks) ** this will pass data back to a main loop later
答案 0 :(得分:1)
您应该为socket.timeout
例外添加处理程序:
import http.client
import socket
activeTanks = 4 # no semicolon here
myTanks = [100, 100, 100, 100]
for tank in range(0, activeTanks):
tankAddress = ("192.168.1.4" + str(tank))
conn = http.client.HTTPConnection(tankAddress, timeout=1)
try:
conn.request("GET", "/Switch=Read")
except socket.timeout as st:
# do some stuff, log error, etc.
print('timeout received')
except http.client.HTTPException as e:
# other kind of error occured during request
print('request error')
else: # no error occurred
r1 = conn.getresponse()
# do some stuff with response
myTanks[tank] = int(r1.read().decode('ASCII').split("...")[1])
finally: # always close the connection
conn.close()
print(myTanks)
答案 1 :(得分:0)
和其他语言一样,你会抓住异常并对待它:( N.B。:我把它放在那里,但它取决于你)
** Fluid tank Reader
import http.client
activeTanks = 4;
myTanks=[100,100,100,100]
for tank in range(0,activeTanks):
tankAddress = ("192.168.1.4"+str(tank))
conn = http.client.HTTPConnection(tankAddress, timeout=1)
## How do I handle the exception and finish the For Loop?
try:
conn.request("GET", "/Switch=Read")
r1 = conn.getresponse()
myTanks[tank] = int(r1.read().decode('ASCII').split("...")[1])
except http.client.HTTPException:
do something
finally:
conn.close() #ensures you cleanly close your connection each time, thanks @schmee
print(myTanks) ** this will pass data back to a main loop later