面向过程的程序设计-协成函数的应用

day24

面向过程的编程思想:

流水线式的编程思想,在设计程序时,需要把整个流程设计出来

优点:

1. 体系结构更加清晰

2. 简化程序的复杂度

缺点:

·1. 可扩展性极其的差,所以说面向过程的应用场景是:不需要经常变化的软件

例子:

需求:实现如linux中 grep -rl "python" /etc/ 的效果,输出/etc/目录下文件中带有python的文件名路径

import os


def init(func):
    "这个装饰器用于执行第一next"

    def wrapper(*args, **kwargs):
        res = func(*args, **kwargs)
        next(res)
        return res

    return wrapper


@init
def search(target):
    "获取文件名"

    while True:
        dir_path = yield
        g = os.walk(dir_path)
        for dirname in g:
            for filename in dirname[-1]:
                file_path = "%s\%s" % (dirname[0], filename)
                target.send(file_path)


@init
def openfile(target):
    "打开文件"

    while True:
        file_path = yield
        with open(file_path) as f:
            target.send((file_path, f))  # 传两个值的时候要以元组的形式


@init
def cat(target):
    "检索文件内容"
    while True:
        file_path, f = yield
        for line in f:
            target.send((file_path, line))


@init
def grep(keyword, target):
    "过滤文件内容"

    while True:
        file_path, line = yield
        if keyword in line:
            target.send(file_path)


@init
def printer():
    "打印文件路径"

    while True:
        file_path = yield
        print(file_path)


o = search(openfile(cat(grep("python", printer()))))
o.send("E:\\test")

运行结果:

E:\test\a.txt
E:\test\a2\a3.txt

版权声明:
作者:admin
链接:https://www.chenxie.net/archives/1647.html
来源:蜀小陈
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>