2013-07-25 42 views
1

我只是想發送請求,但不想浪費時間等待響應。因爲這些回覆對我來說毫無用處。 我擡頭看python文檔,但沒有找到解決方案。 感謝您的任何建議。 我試圖使用 urllib2.urlopen(url, timeout=0.02) 但我不能確定請求是否實際發出。使用urllib2.urlopen()加載一個URL而不等待回覆

回答

4

這被稱爲異步加載,這裏是一個blog post explaining how to do it with urllib2。示例代碼:

#!/usr/bin/env python 

import urllib2 
import threading 

class MyHandler(urllib2.HTTPHandler): 
    def http_response(self, req, response): 
     print "url: %s" % (response.geturl(),) 
     print "info: %s" % (response.info(),) 
     for l in response: 
      print l 
     return response 

o = urllib2.build_opener(MyHandler()) 
t = threading.Thread(target=o.open, args=('http://www.google.com/',)) 
t.start() 
print "I'm asynchronous!" 

這將加載URL而不等待響應。