Python请求有时会冻结

Can*_*kel 8 python multithreading long-polling python-requests

我有一个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.")
Run Code Online (Sandbox Code Playgroud)

我在使用Raspbian OS的Raspberry Pi 2硬件上执行此操作.

当我使用Python 2.7时,我使用了同样的程序而没有任何问题.最近我切换到Python 3.5.我使用2.8.1和2.9.1的两个请求版本进行了测试.

此问题不会经常发生,但在不同的线程上每天发生2-3次.

可能是什么问题?我该怎么调试呢?

编辑:通过更新Linux内核解决了这个问题.

Joh*_*ery 6

根据文件:

http://docs.python-requests.org/en/master/user/quickstart/#timeouts

Timeout超时发生时应抛出异常.这意味着这条线:

print("This line does not print when freeze occurs")
Run Code Online (Sandbox Code Playgroud)

永远不会被称为超时实际发生.

你是否正在捕捉异常?还是其他任何例外?这可能是时机不错,但你只是没有看到这一点.也许尝试这样的事情:

try:
    response = requests.head(poll_request_url, timeout=180)
except requests.exceptions.Timeout:
    print("Timeout occurred")
Run Code Online (Sandbox Code Playgroud)

所以你可以看看这是不是正在发生的事情.

编辑:可能是"连接"步骤没有正确计时.可能是"连接"步骤的大超时值正在以某种方式弄乱它.也许尝试更短的超时(如这里提到的):

http://docs.python-requests.org/en/master/user/advanced/#timeouts

例如

response = requests.head(poll_request_url, timeout=(3, 180))
Run Code Online (Sandbox Code Playgroud)

没有它可能是某种DNS查找问题?也许看看硬编码IP是否会出现同样的问题?

  • 我正在捕获包括Timeout在内的所有异常,并且当超时发生时它会成功捕获异常.当超时没有发生并且冻结发生时,该行永远不会被执行并且不会抛出异常. (3认同)