zoukankan      html  css  js  c++  java
  • Python基础之面向过程编程

      要求:在文件里递归找到关于包含“Python”内容的文件的绝对路径并打印出来

    #定义阶段
    import os,time
    def init(func): #装饰器的作用是使下面的生成器初始化,yield等着被传值
        def wrapper(*args,**kwargs):
            res = func(*args,**kwargs)
            next(res) #调用生成器初始化
            return res
        return wrapper
    @init
    def search(target):
        '''找到文件的绝对路径'''
        while True:
            dir_name = yield
            print("search开始工作:文件的绝对路径")
            time.sleep(2) #加上睡眠时间是为了使看着更有效果
            g = os.walk(dir_name)
            for i in g:
                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,encoding="utf8") as f:
                target.send((file_path,f))
    @init
    def cat(target):
        '''读取文件内容'''
        while True:
            file_path,f = yield
            print("cat开始工作:读取文件内容")
            time.sleep(0.3) #加上睡眠时间是为了使看着更有效果
            for line in f:
                target.send((file_path,line))
    @init
    def grep(pattern,target):
        '''过滤一行内容中有需要内容,就把路径传给下面'''
        while True:
            file_path,line = yield
            print("grep开始工作:过滤内容")
            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("E:michael")
    ---------------以下是输出结果------------------
        E:michaelaa1.txt
        E:michaelaaa1.txt
    

      面向过程的编程思想:

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

      优点:

        1:体系结构更加清晰

        2:简化程序的复杂度

      缺点:

        可扩展性极其的差,所以说面向过程的应用场景是,不需要经常变化的软件,如:linux内核,httpd,git等软件。

  • 相关阅读:
    NOIP2008双栈排序[二分图染色|栈|DP]
    洛谷P1108 低价购买[DP | LIS方案数]
    洛谷P1330封锁阳光大学[二分图染色]
    NOIP模板整理计划
    期中考试
    UVA 10564 Paths through the Hourglass[DP 打印]
    UVA 11404 Palindromic Subsequence[DP LCS 打印]
    POJ2479 Maximum sum[DP|最大子段和]
    POJ3160 Father Christmas flymouse[强连通分量 缩点 DP]
    UVA11324 The Largest Clique[强连通分量 缩点 DP]
  • 原文地址:https://www.cnblogs.com/Michael--chen/p/6699494.html
Copyright © 2011-2022 走看看