1 def demo():
 2     for i in range(4):
 3         yield i
 4 
 5 g=demo()
 6 
 7 g1=(i for i in g)
 8 g2=(i for i in g1)
 9 
10 print(list(g1))
11 print(list(g2))
1
 1 def add(n,i):
 2     return n+i
 3 
 4 def test():
 5     for i in range(4):
 6         yield i
 7 
 8 g=test()
 9 for n in [1,10]:
10     g=(add(n,i) for i in g)
11 
12 print(list(g))
2
 1 def add(n,i):
 2     return n+i
 3 
 4 def test():
 5     for i in range(4):
 6         yield i
 7 
 8 g=test()
 9 for n in [1,10]:
10     g=(add(n,i) for i in g)
11 
12 print(list(g))
13 
14 复制代码
15 
16  
17 
18 复制代码
19 import os
20 
21 def init(func):
22     def wrapper(*args,**kwargs):
23         g=func(*args,**kwargs)
24         next(g)
25         return g
26     return wrapper
27 
28 @init
29 def list_files(target):
30     while 1:
31         dir_to_search=yield
32         for top_dir,dir,files in os.walk(dir_to_search):
33             for file in files:
34                 target.send(os.path.join(top_dir,file))
35 @init
36 def opener(target):
37     while 1:
38         file=yield
39         fn=open(file)
40         target.send((file,fn))
41 @init
42 def cat(target):
43     while 1:
44         file,fn=yield
45         for line in fn:
46             target.send((file,line))
47 
48 @init
49 def grep(pattern,target):
50     while 1:
51         file,line=yield
52         if pattern in line:
53             target.send(file)
54 @init
55 def printer():
56     while 1:
57         file=yield
58         if file:
59             print(file)
60 
61 g=list_files(opener(cat(grep('python',printer()))))
62 
63 g.send('/test1')
64 
65 协程应用:grep -rl /dir
3

 

posted on 2017-08-03 16:17  海燕。  阅读(421)  评论(0编辑  收藏  举报