本文介绍了python 一次尝试,除了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My problem is very simple.I have a try/except code. In the try I have some http requests attempts and in the except I have several ways to deal with the exceptions I'm getting.

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

Now I want to add a time parameter to my code. Which means the try will only last for 'n' seconds. otherwise catch it with except.

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

In free language it would appear as:

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

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

this is mid-code. Not a function. and I have to catch the timeout and handle it. I cannot just continue the code.

        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)

The solution I need is for the try (for 10 seconds)and the except (timeout, after 10 seconds)

推荐答案

查看文档

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

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

If you want to catch more specific errors check this 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 或在此帖子

这篇关于python 一次尝试,除了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 09:34