函数5—协程函数的有应用

协程函数的应用:找到一个文件夹下所有包含python字符串的文件的绝对路径
为生成器函数添加初始化功能的装饰器
import os ,time
def init(func):
def wrapper(*args,**kwargs):
res = func(*args,**kwargs)
next(res)
return res #返回初始化之后的生成器
return wrapper

下面的每一个函数都是一个生成器函数,可以接收生成器发送的值,
同时也是一个生成器,可以发送下面的函数想要的内容
可以实现函数之间的相互通信,完成整个流程,即面向过程的编程风格,函数就是面向过程的程序设计的基本单元
@init
def search(target):
while True:
dir_name = yield
print('找到文件绝对路径')
time.sleep(2)
g = os.walk(dir_name)
for i in g:
for j in i[-1]:
file_path = '%s\%s'%(i[0],j)

target.send(file_path)
@init
def opener(target):
while True:
file_path = yield
print('打开文件')
time.sleep(2)
with open(file_path) as f:
target.send((f,file_path)) #生成器在向函数发送参数时,以元组的形式发送,
# 所以发送多个参数时,要加上()表示元组
@init
def cat(target):
while True:
f,file_path= yield
print('读取文件')
time.sleep(2)
for line in f :
target.send((file_path,line))
@init
def grep(pattern,target):
while True:
file_path,line = yield
print('找到包含python的文件')
time.sleep(2)
if pattern in line:
target.send(file_path)
@init
def printer():
while True:
file_path = yield
print('打印文件路径')
time.sleep(2)
print(file_path)


g=search(opener(cat(grep('python',printer()))))
g.send('F:\egon')
原文地址:https://www.cnblogs.com/liuguniang/p/6714944.html