# 面向过程的编程思想: # 核心是"过程"二字,过程即流程,指的是做事的步骤:先什么、再什么、后干什么 # 基于该思想编写程序就好比在设计一条流水线 # 优点:复杂的问题流程化、进而简单化 # 缺点:扩展性非常差 # 面向过程的编程思想应用场景解析: # 1、不是所有的软件都需要频繁更迭:比如编写脚本 # 2、即便是一个软件需要频繁更迭,也不并不代表这个软件所有的组成部分都需要一起更迭
示例:(实现grep -rl )
import os # g=os.walk(r"E:oldboymy_codegrep-rla") #得到一个生成器 # # print(g) # for pardir,_,files in g: # for file in files: # abs_path=r"{}\{}".format(pardir,file) # print(abs_path) #打印E:oldboymy_codegrep-rla下所有文件的绝对路径 # E:oldboymy_codegrep-rla\a.txt # E:oldboymy_codegrep-rla\b.txt # E:oldboymy_codegrep-rlad\d.txt # E:oldboymy_codegrep-rlac\c.txt # E:oldboymy_codegrep-rlace\e.txt def init(func): def inner(*args,**kwargs): g=func(*args,**kwargs) next(g) return g return inner #第一步:拿到一个文件夹下所有文件的绝对路径 @init def search(target): while True: filepath=yield g=os.walk(filepath) for pardir,_,files in g: for file in files: abs_path=r"{}{}".format(pardir,file) # print(abs_path) #打印E:oldboymy_codegrep-rla下所有文件的绝对路径 target.send(abs_path) #把abs_path传给下一阶段opener() #第二步:打开文件拿到文件对象f @init def opener(target): while True: abs_path=yield with open(abs_path,"r",encoding="utf-8") as f: #把(abs_path,f)传给下一个阶段cat() target.send((abs_path,f)) #第三步:读取f的每一行内容 @init def cat(target): while True: abs_path,f=yield for line in f: #把(abs_path,line)传给下一个阶段grep() res=target.send((abs_path, line)) #满足某种条件,break掉for循环 if res: break #第四步:判断python in line @init def grep(target,pattern): res = False #满足变量先定义后使用 while True: abs_path,line=yield res res=False #每次打开新文件都默认为False if pattern in line: #把abs_path传给下一个阶段 res=True #当line中有匹配字段,通知上一阶段跳出for target.send(abs_path) #第五步:打印文件路径 @init def printer(): while True: abs_path=yield print("{}".format(abs_path)) g=search(opener(cat(grep(printer(),"python")))) g.send(r"E:oldboymy_codegrep-rla")