Python请求超时参数被忽略

2024-10-01 11:25:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python2.7,我希望每个请求在几秒钟后超时,但是请求几乎立即超时。下面是我的代码。在

requestsTimeout = 5
link = 'http://' + IP + '/api/v1.0/system/info'
while (1):
    try:
        return requests.get(link, timeout = requestsTimeout)
    except requests.exceptions.RequestException as e:
        log._print0(_printID, 'getting DAQ Info' ,str(e)) # just printing
        time.sleep(0.1)

现在,如果我断开wifi,每隔5秒就会有一个超时异常的打印输出,但我的打印速度非常快(一秒钟内打印多次)。在


Tags: 代码ipinfoapihttpgetreturntimeout
1条回答
网友
1楼 · 发布于 2024-10-01 11:25:21

当主机不可访问时,ConnectionError在没有timeout设置的等待时间的情况下引发。您可以通过单独处理此异常来克服此问题:

requestsTimeout = 5
link = 'http://' + IP + '/api/v1.0/system/info'
while True:
    try:
        return requests.get(link, timeout=requestsTimeout)
    except requests.exceptions.ConnectionError as e:
        time.sleep(requestsTimeout)
    except requests.exceptions.RequestException as e:
        log._print0(_printID, 'getting DAQ Info' ,str(e)) # just printing
        time.sleep(0.1)

相关问题 更多 >