1. 程式人生 > >Python學習筆記--gevent巢狀使用

Python學習筆記--gevent巢狀使用

這篇主要是接著上篇的,實驗gevent巢狀使用,看情況如何。還是先上程式碼。

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Date    : 2020-03-02 19:53:11
 4 # @Author  : Flyinghappy ([email protected])
 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:呵呵呵,說明實驗成功了!可以巢狀使用。

&n