python的学习之旅---回调机制

Posted 恩是的

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python的学习之旅---回调机制相关的知识,希望对你有一定的参考价值。

回调机制

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      

 

以上是关于python的学习之旅---回调机制的主要内容,如果未能解决你的问题,请参考以下文章

我的C语言学习进阶之旅解决 Visual Studio 2019 报错:错误 C4996 ‘fscanf‘: This function or variable may be unsafe.(代码片段

我的C语言学习进阶之旅解决 Visual Studio 2019 报错:错误 C4996 ‘fscanf‘: This function or variable may be unsafe.(代码片段

Python学习之旅---多态(类的相关知识)

我的OpenGL学习进阶之旅NDK开发中find_library查找的系统动态库在哪里?

我的OpenGL学习进阶之旅NDK开发中find_library查找的系统动态库在哪里?

python学习之旅-06 之小数据池,编码