from twisted.web.client import getPage, defer from twisted.internet import reactor def callback(contents): print(contents) url_list = ['http://www.bing.com', 'http://www.baidu.com', ] for url in url_list: deferred = getPage(bytes(url, encoding='utf8')) deferred.addCallback(callback) reactor.run()
事件執行只有開始沒有結束,所以須要規定某個目標任務的完成來終止事件react
from twisted.web.client import getPage, defer from twisted.internet import reactor def callback(contents): print(contents) url_list = ['http://www.bing.com', 'http://www.baidu.com', ] _active = [] for url in url_list: d = getPage(bytes(url, encoding='utf8')) d.addCallback(callback) _active.append(d) def all_done(arg): reactor.stop() xx = defer.DeferredList(_active) xx.addBoth(all_done) reactor.run()
將defer對象加入一個列表_active中以此來用defer方法DeferredList來監聽該列表中的任務是否完成回調,在執行回調以後addBoth(表示不管錯誤仍是成功都會執行該方法設置的函數)web