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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:16:14  来源:igfitidea点击:

setting the timeout on a urllib2.request() call

pythonurllib2

提问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()因为我使用的datarequest. 我该如何设置?

采纳答案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

Why not use the awesome requests? You'll save yourself a lot of time.

为什么不使用很棒的请求?你会为自己节省很多时间。

If you are worried about deployment just copy it in your project.

如果您担心部署,只需将其复制到您的项目中即可。

Eg. of requests:

例如。请求数:

>>> requests.post('http://github.com', data={your data here}, timeout=10)

回答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 :)

这也有效:)