面向过程的程序设计

面向过程的程序设计

    需求:有一个文件夹,在文件里有多个子文件夹,多个子文件夹里有多个文件。

        现需要将文件中有Python关键字的文件,打印出所在的文件路径。

        类似于Linux是grep -rl 'root' /etc 命令。

    小点:

      os模块下的walk。可以遍历出指定路径下的内容。     

#grep -rl 'python' C:George
import os,time
def init(func):
    def wrapper(*args,**kwargs):
        res=func(*args,**kwargs)
        next(res)
        return res
    return wrapper

#找到一个绝对路径,往下一个阶段发一个
@init
def search(target):
    '找到文件的绝对路径'
    while True:
        dir_name=yield #dir_name='C:\George'
        print('车间search开始生产产品:文件的绝对路径')
        time.sleep(2)
        g = os.walk(dir_name)
        for i in g:
            # print(i)
            for j in i[-1]:
                file_path = '%s\%s' % (i[0], j)
                target.send(file_path)

@init
def opener(target):
    '打开文件,获取文件句柄'
    while True:
        file_path=yield
        print('车间opener开始生产产品:文件句柄')
        time.sleep(2)
        with open(file_path) as f:
            target.send((file_path,f))

@init
def cat(target):
    '读取文件内容'
    while True:
        file_path,f=yield
        print('车间cat开始生产产品:文件的一行内容')
        time.sleep(2)
        for line in f:
            target.send((file_path,line))

@init
def grep(pattern,target):
    '过滤一行内容中有无python'
    while True:
        file_path,line=yield
        print('车间grep开始生产产品:包含python这一行内容的文件路径')
        time.sleep(0.2)
        if pattern in line:
            target.send(file_path)

@init
def printer():
    '打印文件路径'
    while True:
        file_path=yield
        print('车间printer开始生产产品:得到最终的产品')
        time.sleep(2)
        print(file_path)



g=search(opener(cat(grep('python',printer()))))
g.send('C:\George')
g.send('D:\dir1')
g.send('E:\dir2')

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

    优点:

        #1:体系结构更加清晰

        #2:简化程序的复杂度

 

    缺点:

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

       如:linux内核,httpd,git等软件。

原文地址:https://www.cnblogs.com/george92/p/9106995.html