首页 > 技术文章 > python的学习之旅---回调机制

surehunter 2017-11-25 20:32 原文

回调机制

import requests

需要 requests 模块的支持

 

需要回调函数的场景:进程池中任何一个任务一旦处理完了,就立即告知主进程:我好了额,你可以处理我的结果了。主进程则调用一个函数去处理该结果,该函数即回调函数

我们可以把耗时间(阻塞)的任务放到进程池中,然后指定回调函数(主进程负责执行),这样主进程在执行回调函数时就省去了I/O的过程,直接拿到的是任务的结果。

 1 from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
 2 import requests
 3 import os
 4 import time
 5 
 6 def get(url):
 7     print('%s GET %s' %(os.getpid(),url))
 8     response=requests.get(url)
 9     if response.status_code == 200:
10         return {'url':url,'text':response.text}
11 
12 def parse(res):
13     res=res.result()
14     url=res['url']
15     text=res['text']
16     print('%s parse %s res:%s' %(os.getpid(),url,len(text)))
17 
18 if __name__ == '__main__':
19     urls = [
20         'https://www.baidu.com',
21         'https://www.python.org',
22         'https://www.openstack.org',
23         'https://help.github.com/',
24         'http://www.sina.com.cn/'
25     ]
26 
27     # p=ProcessPoolExecutor()
28     # start=time.time()
29     # l=[]
30     # for url in urls:
31     #     furture=p.submit(get,url)
32     #     l.append(furture)
33     # p.shutdown(wait=True)
34     #
35     # for furture in l:
36     #     parse(furture)
37     #
38     # print(time.time()-start) #4.504257440567017
39 
40     p=ProcessPoolExecutor()
41     start=time.time()
42     for url in urls:
43         future=p.submit(get, url)
44         future.add_done_callback(parse) #parse(futrue)
45     p.shutdown(wait=True)
46     print(time.time()-start) #3.1761815547943115
47     print(os.getpid())

 

future=p.submit(get, url)                             

future.add_done_callback(parse)                #parse(futrue)     把future对象传给回调函数 parse 通过对象的 .result 获取future的 return的值

也就是说如果使用回调函数, 子进程的函数必须要写返回值。想要拿到返回值 必须要用    .result      

 

推荐阅读