python Time一个尝试例外

2024-05-19 00:00:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

现在我想在代码中添加一个时间参数。这意味着尝试只会持续“n”秒。否则就用“除非”。

在自由语言中,它将显示为:

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)


Tags: 代码forresponserequesturllib2requrlopenseconds
2条回答

检查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或此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 

相关问题 更多 >

    热门问题