python 时间一试,除了

python Time a try except

我的问题很简单。 我有一个 try/except 代码。在 try 中,我尝试了一些 http 请求,在 except 中,我有几种方法来处理我遇到的异常。

现在我想在我的代码中添加一个时间参数。这意味着尝试只会持续 'n' 秒。否则用 except 捕获它。

在自由语言中它会显示为:

try for n seconds:
    doSomthing()
except (after n seconds):
    handleException()

这是中间代码。不是函数。我必须赶上超时并处理它。我不能继续代码。

        while (recoveryTimes > 0):
            try (for 10 seconds):

                urllib2.urlopen(req)
                response = urllib2.urlopen(req)     
                the_page = response.read()
                recoveryTimes = 0

            except (urllib2.URLError, httplib.BadStatusLine) as e:
                print str(e.__unicode__())
                print sys.exc_info()[0]
                recoveryTimes -= 1

                if (recoveryTimes > 0):
                    print "Retrying request. Requests left %s" %recoveryTimes
                    continue
                else:
                    print "Giving up request, changing proxy."
                    setUrllib2Proxy()
                    break
            except (timedout, 10 seconds has passed)
                setUrllib2Proxy()
                break

我需要的解决方案是 try (for 10 seconds)except (timeout, after 10 seconds)

勾选 documentation

import urllib2
request = urllib2.Request('http://www.yoursite.com')
try:
    response = urllib2.urlopen(request, timeout=4)
    content = response.read()
except urllib2.URLError, e:
    print e

如果您想捕获更具体的错误,请检查此 post

或者请求

import requests
try:
    r = requests.get(url,timeout=4)
except requests.exceptions.Timeout as e:
    # Maybe set up for a retry
    print e

except requests.exceptions.RequestException as e:
    print e

有关使用请求时的异常的更多信息,请参阅 docs or in this post

如果您使用的是 UNIX,则通用解决方案:

import time as time
import signal

#Close session
def handler(signum, frame):
    print 1
    raise Exception('Action took too much time')


signal.signal(signal.SIGALRM, handler)
signal.alarm(3) #Set the parameter to the amount of seconds you want to wait

try:
    #RUN CODE HERE

    for i in range(0,5):
        time.sleep(1)
except:
    print 2

signal.alarm(10) #Resets the alarm to 10 new seconds
signal.alarm(0) #Disables the alarm