这篇主要是接着上篇的,实验gevent嵌套使用,看情况如何。还是先上代码。

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

View Code

再来看看运行结果哈:我截图了两张,大家可以仔细对比一下。说明是异步执行的。

另外一张截图

 

 PS:呵呵呵,说明实验成功了!可以嵌套使用。

 

版权声明:本文为flyinghappy原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/flyinghappy/p/12397917.html