2013-05-20 22 views
14

超時我需要設置urllib2.request()超時。設置在urllib2.request()調用

我不使用urllib2.urlopen(),因爲我使用request的參數data。我該如何設置?

+0

要全局設置超時,你可以使用'socket.setdefaulttimeout()' – Mark

回答

33

雖然urlopen不接受data參數有關POST,你可以一個Request對象這樣的呼籲urlopen

import urllib2 
request = urllib2.Request('http://www.example.com', data) 
response = urllib2.urlopen(request, timeout=4) 
content = response.read() 
+6

什麼單位是timeout? –

+2

@MöbiusStripMallSeconds([manual](https://docs.python.org/2/library/urllib2.html)) – carla

2

爲什麼不使用真棒requests?你會節省很多時間。

如果您擔心部署,請將其複製到您的項目中。

例如,

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

的是,你能避免使用的urlopen然後像這樣:

請求
request = urllib2.Request('http://example.com') 
response = opener.open(request,timeout=4) 
response_result = response.read() 

This works too :) :)

+1

不使用urlopen有什麼好處? – NumenorForLife

相關問題