#应用:grep -rl 'root' /etc
import os
def deco(func):
def wrapper(*args):
g=func(*args)
next(g)
return g
return wrapper
start_path=r'/Users/mona/Desktop/python学习/study/a'
#阶段一:递归地找文件的绝对路径,把路径给阶段二
@deco
def search_func(target):
while True:
start_path=yield
g=os.walk(start_path)
for par_dir,_,files in g:
for file in files:
file_path=r'%s/%s'%(par_dir,file)
target.send(file_path)
#阶段二:收到文件路径,打开文件获取对象,并把文件对象发给阶段三
@deco
def open_func(target):
while True:
file_path=yield
with open(file_path,'r',encoding='utf-8') as f:
target.send((file_path,f))
#阶段三收到文件对象,读取每一行,并把内容发给阶段四
@deco
def cat_func(target):
while True:
file_path,f=yield
for line in f :
res=target.send((file_path,line))
if res:
break
#阶段四:收到内容,判断root是否在内容中,把符合条件的文件名发给阶段五
@deco
def gerp_func(target,pattern):
tag=False
while True:
file_path,line=yield tag
tag=False
if pattern in line:
target.send(file_path)
tag=True
#阶段五:收到文件名,并打印
@deco
def printer_func():
while True:
filename=yield
print(filename)
g=search_func(open_func(cat_func(gerp_func(printer_func(),'root'))))
g.send(start_path)