python尝试除外

Era*_*she 4 python timer try-catch

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

现在我想在我的代码中添加一个时间参数.这意味着尝试只会持续'n'秒.否则接受它除外.

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

try for n seconds:
    doSomthing()
except (after n seconds):
    handleException()
Run Code Online (Sandbox Code Playgroud)

这是中码.不是功能.我必须抓住超时并处理它.我不能只是继续代码.

        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
Run Code Online (Sandbox Code Playgroud)

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

Aja*_*jay 5

查看文档

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
Run Code Online (Sandbox Code Playgroud)

如果您想捕获更具体的错误,请查看此帖子

或者对于请求

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
Run Code Online (Sandbox Code Playgroud)

更多关于异常,同时使用要求中可以找到的文档或在这个岗位


Tom*_*m O 5

如果您使用的是 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 
Run Code Online (Sandbox Code Playgroud)