我正在使用Python 2.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)
现在,如果我断开无线网络连接,应该每隔5秒钟就收到一次超时异常的打印输出,但是我得到的打印速度非常快(在一秒钟内多次)。
答案 0 :(得分:3)
当主机不可访问时,将引发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)