Python--函数式编程

运用yield实现

  模拟 grep -rl 'root' /etc (递归找etc下所有文件并打开,过滤有'root'的文件)

# import os
# g = os.walk(r'C:\Users\56360\Desktop\city\mycity')
# print(next(g))  # 拿到当前文件夹下的子目录和子文件 格式:('C:\Users\56360\Desktop\city\mycity',['src', 'static', 'test'],['index.html', 'package-lock.json', 'package.json'])
# print(next(g))  # 会进入src目录,依次类推,知道有子文件时,进行拼接就拿到绝对路劲
import os
def init(func):
    def wrapper(*args,**kwargs):
        g=func(*args,**kwargs)
        next(g)
        return g
    return wrapper
#阶段一:递归地找文件的绝对路径,把路径发给阶段二
@init
def search(target):
    'search file abspath'
    while True:
        start_path=yield
        g = os.walk(start_path)
        for par_dir, _, files in g:
            # print(par_dir,files)
            for file in files:
                file_path = r'%s\%s' % (par_dir, file)
                target.send(file_path)
#阶段二:收到文件路径,打开文件获取获取对象,把文件对象发给阶段三
@init
def opener(target):
    'get file obj: f=open(filepath)'
    while True:
        file_path=yield
        with open(file_path,encoding='utf-8') as f:
            target.send((file_path,f))
 
#阶段三:收到文件对象,for循环读取文件的每一行内容,把每一行内容发给阶段四
@init
def cat(target):
    'read file'
    while True:
        filepath,f=yield
        for line in f:        # 有多少行就循环多少行
            res=target.send((filepath,line))
            if res:
                break
 
#阶段四:收到一行内容,判断root是否在这一行中,如果在,则把文件名发给阶段五
@init
def grep(target,pattern):
    'grep function'
    tag=False
    while True:
        filepath,line=yield tag #target.send((filepath,line))   返回tag给上个阶段,当为true时就不要循环了
        tag=False      
        if pattern in line:
            target.send(filepath)
            tag=True        
#阶段五:收到文件名,打印结果
@init
def printer():
    'print function'
    while True:
        filename=yield
        print(filename)
 
start_path1=r'F:\text'
# start_path2=r''
g=search(opener(cat(grep(printer(),'root'))))
 
print(g)
g.send(start_path1)

  

这个程序是一步步流水线式的流程,这就是面向过程编程

面向过程:

  原始的编程思想,先做什么,再做什么,有几个阶段,一步步实现,流水线形式的

优点:

  思路清晰,复杂问题流程化

缺点:

  只要有一个流程出错,那么全部挂掉,扩展性差

猜你喜欢

转载自www.cnblogs.com/Mr-chenshuai/p/9954390.html