In fact, this process-oriented programming, is the basis for writing programs, so must be well mastered
This program involves knowledge points: adorners, generators, and coprocessor applications
1 #edited by: Shanlong2 ImportOS3DISTINCT = []#define a list of files for judging duplicates4 defAutonext (Target):#next decorator for the generator5 defNexttarget (*args):6res = Target (*args)#res get target (*args) execution result (target ())7Next (RES)#let Res perform a next-to-yield operation8 returnRes#returns the current state of res (next to yield)9 returnNexttargetTen One@AutoNext#call the builder's next adorner A defInputgetpath (Target): -InputPath =yield #InputPath The return value waiting for yield -Pathgen = Os.walk (InputPath)#return the directory subdirectory and files in InputPath to the list [path, [subdirectory],[file]] the forIinchPathgen: - forJinchI[-1]: -FilePath ="%s\\%s"% (I[0],J)#pass the formatted path to the FilePath -Target.send (FilePath)#use Send to pass a value to yield in target + - @AutoNext + defOpenFile (Target): A whileTrue: atF =yield#F waits for the return value of Yild, which is passed by Target.send in InputPath () . -With open (f) as F:#assign an F path file open to F -Target.send ((f,f))#since the final file path is to be displayed, this is to pass two values in tuples to the next target in Yield,f is the file handle, and F is the file path - #("Asdfasdf", "F:\\a\\a.txt") - @AutoNext - defCatfile (Target): in whileTrue: -F,f =yield#the upper OpenFile has passed the F and F values to yield here and returns to F,f, since OpenFile passes two values, it is also used to receive two values . to #f= "Asdfasdf", f= "F:\\a\\a.txt " + forIinchF: -Target.send ((i,f))#as with send in OpenFile, the value of I and the value of F are passed to yield in the next target the * @AutoNext $ defGrepline (TARGET,CHIOCE):#Chioce is the keyword to be retrieved by user inputPanax Notoginseng whileTrue: -Line,f =yield#Also, two parameters are used to receive the yield return value the if(ChioceinchLine ): +Target.send (F)#There is no need to pass two values here, because the last target only needs to be a file path. A the @AutoNext + defprintinfo (): - whileTrue: $F =yield $ if(F not inchDISTINCT):#append f to the distinct list when f this path value does not exist in distinct - distinct.append (F) - Print(F) the -Chioce = input ("Please enter the keywords you want to retrieve:")Wuyi #Here's the call in fact, not difficult, careful analysis will be easy to understand theGene =Inputgetpath (OpenFile (Catfile (Grepline (Printinfo (), Chioce) )) - Try:#exception handling for stop alarms WuGene.send ("f:\\a") - exceptstopiteration: About Print("Search Complete")
Python exercises-process-oriented programming-simulating grep commands