首页 > 编程语言 > 详细

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

时间:2020-03-02 21:17:51      阅读:80      评论:0      收藏:0      [点我收藏+]

主要分享一下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的嵌套使用!看能不能实现并发的效果!

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

原文:https://www.cnblogs.com/flyinghappy/p/12397341.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!