处理 Python HTTP 连接超时



我正在尝试从四个使用 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

您应该为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)

与其他语言一样,您可以捕获异常并处理它:(注意:我把它放在那里,但这取决于你(

** 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

相关内容

  • 没有找到相关文章

最新更新