我有一个Python程序,发送几个(大约5-6)长的轮询请求并行使用不同的线程每个轮询通过请求包。我意识到我的一些线程有时会死机。当发生这种情况时,我发送请求的服务器不会收到请求。此外,我对请求设置了超时,但它不起作用。
try:
print("This line prints")
response = requests.head(poll_request_url, timeout=180)
print("This line does not print when freeze occurs")
except ReadTimeout:
print("Request exception.")
except RequestException as e:
print("Request exception.")
except Exception:
print("Unknown exception.")
print("This line does not print either when freeze occurs.")我是在Raspberry Pi 2硬件和Raspbian OS上这样做的。
当我使用Python 2.7时,我使用了同样的程序,没有任何问题。最近我切换到了Python3.5。我使用2.8.1和2.9.1两个requests版本进行了测试。
这个问题不经常发生,但每天在不同的线程上发生2-3次。
可能的问题是什么?我如何调试它呢?
编辑:这个问题可以通过更新Linux内核来解决。
发布于 2016-02-09 21:08:53
根据文档:
http://docs.python-requests.org/en/master/user/quickstart/#timeouts
当超时发生时,它应该抛出一个Timeout异常。这意味着这一行:
print("This line does not print when freeze occurs")不会被称为实际发生的超时。
你捕捉到异常了吗?或任何其他例外?可能是超时了,但您只是看不到这一点。也许可以试试这样的东西:
try:
response = requests.head(poll_request_url, timeout=180)
except requests.exceptions.Timeout:
print("Timeout occurred")所以你可以看看这是不是发生了什么。
编辑:可能是“连接”步骤没有正确超时。这可能是“连接”步骤的大超时值以某种方式搞乱了它。也许可以尝试更短的超时时间(就像这里提到的):
http://docs.python-requests.org/en/master/user/advanced/#timeouts
例如:
response = requests.head(poll_request_url, timeout=(3, 180))如果做不到,可能是某种DNS查找问题?也许可以看看硬编码IP是否也会出现同样的问题?
发布于 2017-08-17 22:17:27
使用计时器(从线程导入计时器)解决了我的问题。如果在接下来的10秒内没有结果-重复,如果在接下来的10秒内没有结果-打印'Error‘并继续。你不能使用if语句来监控计时器的状态,但是你可以通过while循环来监控计时器的状态,增加time if result is ok (Python: Run code every n seconds and restart timer on condition)。
https://stackoverflow.com/questions/35292083
复制相似问题