zoukankan      html  css  js  c++  java
  • 函数5—协程函数的有应用

    协程函数的应用:找到一个文件夹下所有包含python字符串的文件的绝对路径
    为生成器函数添加初始化功能的装饰器
    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
    print('找到文件绝对路径')
    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('打开文件')
    time.sleep(2)
    with open(file_path) as f:
    target.send((f,file_path)) #生成器在向函数发送参数时,以元组的形式发送,
    # 所以发送多个参数时,要加上()表示元组
    @init
    def cat(target):
    while True:
    f,file_path= yield
    print('读取文件')
    time.sleep(2)
    for line in f :
    target.send((file_path,line))
    @init
    def grep(pattern,target):
    while True:
    file_path,line = yield
    print('找到包含python的文件')
    time.sleep(2)
    if pattern in line:
    target.send(file_path)
    @init
    def printer():
    while True:
    file_path = yield
    print('打印文件路径')
    time.sleep(2)
    print(file_path)


    g=search(opener(cat(grep('python',printer()))))
    g.send('F:\egon')
  • 相关阅读:
    php使用PHPMailer邮件类发送邮件
    apache一个IP一个端口对应多个域名
    网页宽度自动适应手机屏幕宽度的方法
    PHP抓取网页图片
    innodb存储引擎
    mysql存储引擎概述
    mysql事务
    mysql字符集
    mysql数据对象
    SQL-基础学习4--聚集函数:AVG(),COUNT(),MAX(),MIN(),SUM();聚集不同值:DISTINCT
  • 原文地址:https://www.cnblogs.com/liuguniang/p/6714944.html
Copyright © 2011-2022 走看看