协程函数(yield另一种用法)

yield的语句形式:yield 1

yield的表达形式: x=yield

 

 1 #定义函数
 2 def main(func):
 3     """装饰器"""
 4     def wrapper(*args,**kwargs):
 5         """初始函数"""
 6         res = func(*args,**kwargs)
 7         next(res)
 8         return res
 9     return wrapper
10 
11 
12 @main
13 def eate(name):
14     """源代码函数"""
15     print("%s already is eat")
16     food_list = []
17     while True:
18         food = yield food_list
19         food_list.append(food)
20         print("%s start eat %s" %(name,food))
21 #使用
22 g = eate('elax')
23 print("华丽的分割线".center(50,'-'))
24 print(g.send("雾霾"))
25 print(g.send("沙尘暴"))
26 
27 ##结果
28 %s already is eat
29 ----------------------华丽的分割线----------------------
30 elax start eat 雾霾
31 ['雾霾']
32 elax start eat 沙尘暴
33 ['雾霾', '沙尘暴']
View Code

 实际应用

 1 #!/usr/bin/env python
 2 #-*- coding:utf-8 -*-
 3 #A Bao
 4 
 5 import os
 6 
 7 def init_adorn(func):
 8     def wrapper(*args,**kwargs):
 9         res = func(*args,**kwargs)
10         next(res)
11         return res
12     return wrapper
13 
14 @init_adorn
15 def search(target):
16     while True:
17         search_path = yield
18         g = os.walk(search_path)
19         for par_dir,_,files in g:
20             for file in files:
21                 file_abs_path = r'%s\%s'%(par_dir,file)
22                 target.send(file_abs_path)
23 @init_adorn
24 def opener(target):
25     while True:
26         file_abs_path = yield
27         with open(file_abs_path,encoding='utf-8') as f:
28             target.send((file_abs_path,f))
29 @init_adorn
30 def cat(target):
31     while True:
32         file_abs_path,f = yield
33         for line in f:
34             tag = target.send((file_abs_path,line))
35             if tag:
36                 break
37 @init_adorn
38 def grep(target,pattern):
39     tag = False
40     while True:
41         file_abs_path,line = yield tag
42         tag = False
43         if pattern in line:
44             tag = True
45             target.send(file_abs_path)
46 
47 @init_adorn
48 def printer():
49     while True:
50         file_abs_path=yield
51         print(file_abs_path)
52 
53 x=r'C:\Users\admin\PycharmProjects\s17\day5\a'
54 
55 g=search(opener(cat(grep(printer(),'python'))))
56 print(g)
57 g.send(x)
View Code

 

posted @ 2017-05-31 19:00  Sober--Never  阅读(174)  评论(0)    收藏  举报