python协成与面向过程编程
初步了解协程
def eater(): print('start to eat') while True: food=yield print('is eating food:%s'%food) def producer(): dog=eater() next(dog) # 先next一次唤醒协程函数 #然后下面的操作都是dog.send(值) food1='黄瓜' food2='茄子' dog.send(food1) dog.send(food2) producer() 输出结果: start to eat is eating food:黄瓜 is eating food:茄子
面向过程编程
#实现grep -rl 'python' /root/
import os import functools def init(func): @functools.wraps(func) #让warpper的帮助信息同eater相同 def warpper(*args,**kwargs): '我是warpper函数' g=func(*args,**kwargs) next(g) return g return warpper #面向过程的编程 #扩展性差 def get_file(abs_path,target): ''' 生产一个个文件 :param abs_path:传进来的决对路径 :param target: 下一个目标 :return: 返回绝对文件的路径 ''' g=os.walk(abs_path) for top_dir,current_dir,files in g: for file in files: abs_file_path=r'%s\%s' %(top_dir,file) target.send(abs_file_path) @init def opener(target): ''' 打开文件 :return: 返回句柄 :param target 下一个目标 ''' while True: abs_file_path=yield with open(abs_file_path) as f: target.send((f,abs_file_path)) @init def get_lines(target): ''' 读取每一行的内容 :param target: 下一个目标 :return:返回每一行的内容 ''' while True: f,abs_file_path=yield for line in f: target.send((line,abs_file_path)) @init def grep(pattern,target): ''' 过滤关键字 :param pattern:匹配关键字 :param target: 下一个目标 :return: 返回文件 ''' while True: line,abs_file_path=yield if pattern in line: target.send(abs_file_path) @init def printer(): ''' 打印功能 :return:输出信息 ''' while True: abs_file_path=yield print(abs_file_path) get_file(r'D:\test',opener(get_lines(grep('zzl',printer()))))