简体   繁体   English

使用Python urllib2.urlopen检测挂起

[英]Detecting hangs with Python urllib2.urlopen

I'm using Python's urllib2 to send an HTTP post: 我正在使用Python的urllib2发送HTTP帖子:

import socket, urllib, urllib2

socket.setdefaulttimeout(15)    

postdata = urllib.urlencode({'value1' : 'a string', 'value2' : 'another string'})
headers = {
    'User-Agent': 'Agent',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'text/html, */*',
}

try: 
    request = urllib2.Request('http://www.example.com', postData, headers)
    response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
    # Handle here
except urllib2.URLError, e:
    # Handle here
except httplib.HTTPException, e:
    # Handle here

Occasionally a network issue results in the call to urlopen never returning. 偶尔网络问题会导致对urlopen的调用永远不会返回。 We see other errors (including timeouts) handled correctly by the except block and have a call to socket.setdefaulttimeout() but there are still instances where the urlopen will never return. 我们看到except块正确处理了其他错误(包括超时)并调用了socket.setdefaulttimeout(),但仍然存在urlopen永远不会返回的实例。

I know it's never returning because we have some log lines in our actual code which get called before and after, and when this problem occurs only the calls before are made and the script hangs forever. 我知道它永远不会返回,因为我们的实际代码中有一些日志行会在之前和之后被调用,并且当出现此问题时,只会进行之前的调用并且脚本将永久挂起。

What's the best way to detect/handle this? 检测/处理此问题的最佳方法是什么?

You can use signals, first set a handler for your signal 您可以使用信号,首先为信号设置处理程序

import signal
...
def handler(signum, frame):
    print 'Signal handler called with signal', signum
...
signal.signal(signal.SIGALRM, handler)

and put an alarm just before the urlopen call 并在urlopen电话之前发出警报

signal.alarm(5)
response = urllib2.urlopen(request)
signal.alarm(0) # Disable the signal

after 5 seconds (or the time you desire) the OS will call the handler if the alarm is not disable (if urlopen never returns). 在5秒钟(或您想要的时间)之后,如果警报未被禁用(如果urlopen永远不会返回),操作系统将调用处理程序。 More info about signal module: http://docs.python.org/library/signal.html 有关信号模块的更多信息: http//docs.python.org/library/signal.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM