Python学习笔记--gevent库的使用

主要分享一下gevent库的基本使用和代码实测。gevent库让我们按同步编程的方式进行异步编程。还是先上代码,自己亲测!。

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Date    : 2020-03-01 13:59:03
 4 # @Author  : Flyinghappy (671474@qq.com)
 5 # @Link    : https://www.cnblogs.com/flyinghappy/
 6 # @Version : $Id$
 7 from gevent import monkey
 8 monkey.patch_all()
 9 import gevent
10 import time
11 import asyncio
12 import requests
13 import urllib.request
14 def runinfo(func):
15     def inner(*args,**kwargs):
16         print('开始访问---'+str(args[0])+'---'+str(args[1]))
17         start_time=time.time()
18         result=func(*args,**kwargs)
19         stop_time=time.time()
20         print(func.__name__+'------running time is: %s'% (stop_time-start_time))
21         print('结束访问---'+str(args[0])+'---'+str(args[1]))
22         return result
23     return inner
24 @runinfo
25 def taskfun(url,n):
26     html=urllib.request.urlopen(url).read()
27     return html
28 def async_main():  
29     url=[
30     'http://www.sina.com.cn',
31     'http://www.cnr.cn',
32     'http://www.hao123.com',
33     'http://www.taobao.com',
34     'https://www.eastmoney.com'
35     ]
36     start_time=time.time()
37     g_list=[]
38     for i in range(len(url)):
39         g=gevent.spawn(taskfun,url[i],i)
40         g_list.append(g)
41     gevent.joinall(g_list)
42     stop_time=time.time()
43     print('main---running time is: %s'% (stop_time-start_time))
44 if __name__ == '__main__':
45     async_main()
View Code

再看看代码测试结果截图:注意下面两张图的对比哈。说明了上面的代码实现了异步处理的功能。

 

 使用注意事项:

from gevent import monkey
monkey.patch_all()

这段代码一定要放在所有代码最前面哈。猴子补丁也一定要上!不然就还是同步的,没有并发的效果!

大家可以试试gevent的嵌套使用!看能不能实现并发的效果!

猜你喜欢

转载自www.cnblogs.com/flyinghappy/p/12397341.html
今日推荐