Python 在 urllib2.request() 调用上设置超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16646322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
setting the timeout on a urllib2.request() call
提问by eran
I need to set the timeout on urllib2.request().
我需要将超时设置为urllib2.request().
I do not use urllib2.urlopen()since i am using the dataparameter of request. How can I set this?
我不使用,urllib2.urlopen()因为我使用的data是request. 我该如何设置?
采纳答案by Jared
Although urlopendoes accept dataparam for POST, you can call urlopenon a Requestobject like this,
尽管urlopen确实接受dataparam for POST,但您可以调用urlopen这样的Request对象,
import urllib2
request = urllib2.Request('http://www.example.com', data)
response = urllib2.urlopen(request, timeout=4)
content = response.read()
回答by Alex
回答by Giorgoc
still, you can avoid using urlopen and proceed like this:
不过,您可以避免使用 urlopen 并按如下方式进行:
request = urllib2.Request('http://example.com')
response = opener.open(request,timeout=4)
response_result = response.read()
this works too :)
这也有效:)

