Python练习-面向过程编程-模拟Grep命令

其实这个面向过程编写程序,是编写程序的基础,所以一定要好好掌握

此程序涉及知识点:装饰器,生成器,协程器应用

 1 # 编辑者:闫龙
 2 import os
 3 Distinct = [] #定义一个列表用于判断重复的文件
 4 def AutoNext(Target): #生成器的Next装饰器
 5     def NextTarget(*args):
 6         res = Target(*args) #res得到Target(*args)的执行结果(Target())
 7         next(res)#让res进行一次next到yield的操作
 8         return res#返回res当前的状态(next到yield的状态)
 9     return NextTarget
10 
11 @AutoNext#调用生成器的Next装饰器
12 def InputGetPath(Target):
13     InputPath = yield #InputPath等待yield的返回值
14     PathGen = os.walk(InputPath)#将InputPath中的目录子目录和文件游走后返回列表[路径,[子目录],[文件]]
15     for i in PathGen:
16         for j in i[-1]:
17             FilePath ="%s\%s"%(i[0],j) #将格式化好的路径传递给FilePath
18             Target.send(FilePath) #使用Send方式传值给Target中的yield
19 
20 @AutoNext
21 def OpenFile(Target):
22     while True:
23         F = yield#F等待yild的返回值,这里是由InputPath()中的Target.send传递过来的
24         with open(F) as f:#将F路径的文件打开赋值给f
25             Target.send((f,F))#由于最后要显示文件路径所以,这里要以元组的方式传递两个值给下一个Target中的yield,f是文件句柄,F是文件路径
26             #("asdfasdf","F:\a\a.txt")
27 @AutoNext
28 def CatFile(Target):
29     while True:
30         f,F = yield#上方的OpenFile已经将f和F值传递到了这里的yield并返回给f,F,既然OpenFile传递了两个值,这里也要用两个值接收
31         #f="asdfasdf",F="F:\a\a.txt"
32         for i in f :
33             Target.send((i,F))#与OpenFile中的send一样,将i的值和F的值传递给下一个Target中的yield
34 
35 @AutoNext
36 def GrepLine(Target,chioce):#chioce是用户输入的即将检索的关键字
37     while True:
38         line,F = yield#同样还是要用两个参数来接收yield的返回值
39         if (chioce in line):
40             Target.send(F) #这里就不需要传递两个值了,因为最后的Target只需要的到文件路径就可以了
41 
42 @AutoNext
43 def PrintInfo():
44     while True:
45         F = yield
46         if(F not in Distinct): #当F这个路径值不存在Distinct中时将F追加到Distinct列表中
47             Distinct.append(F)
48             print(F)
49 
50 chioce = input("请输入你要检索的关键字:")
51 #这里的调用其实,不难,仔细分析一下就能很容易的理解了
52 Gene = InputGetPath(OpenFile(CatFile(GrepLine(PrintInfo(),chioce))))
53 try: #针对Stop告警的异常处理
54     Gene.send("F:\a")
55 except StopIteration:
56     print("检索完成")
原文地址:https://www.cnblogs.com/DragonFire/p/6700832.html