面向过程的协程函数应用:迭代文件夹中文件内容,匹配出带有关键字的文件绝对路径
面向过程的协程函数应用:
python实现查询文件路径下带有python关键字的文件路径功能,类似于linux中:grep -rl 'python' /etc
import os
#函数定义
def init(func):
'装饰器:next()方法装饰给生成器'
def wrapper(*args,**kwargs):
g = func(*args,**kwargs)
next(g)
return g
return wrapper
@init
def search(tar):
'查询全部文件路径'
while True:
root_path=yield
lines = os.walk(root_path)
for i in lines:
for j in i[-1]:
url='%s/%s'%(i[0],j)
tar.send(url)
@init
def opener(tar):
'打开文件'
while True:
url_path = yield
with open(url_path,mode='r',encoding='utf8') as file:
tar.send((url_path,file))
@init
def cat(tar):
'读内容'
while True:
url,file = yield
'''这里捕获异常是因为文件夹下存在.DS_Store隐藏文件,这个文件内
容编码格式和utf8不一致,导致报错UnicodeDecodeError: 'utf-8'
codec can't decode byte 0xd5 in position 318: invalid
continuation byte'''
try:
for i in file:
tar.send((url,i))
except Exception:
pass
@init
def grep(keyword,tar):
'过滤内容'
while True:
url,txt = yield
if keyword in txt:
tar.send(url)
@init
def printer():
'打印内容'
while True:
url = yield
print(url)
#函数调用
g=search(opener(cat(grep('python',printer()))))
g.send('/Users/root/Downloads/testfile')
面向过程的编程思想特点:
1、体系结构清晰
2、降低程序复杂度
3、可扩展性极差,适用于定制化需求,需求不变的功能,例如:操作系统内核、httpd、github等