yield的表达式用法 模拟linuxGrep命令

模拟grep命令 使用yield 接收

目录 结构

a

-------b

b.txt

a.txt

文件里面写上包含的关键字 如Python  


#!/usr/bin/env python
# -*- coding:utf-8 -*-

#此为最终结果  已经可以查找到有关键字的文件
'''
grep -rl 'python' /root
'''
import os

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

@init #生成器调用装饰器
def search(target):
    '''取出所有文件路径'''
    #更改为生成器
    while True:
        search_path = yield
        g=os.walk(search_path)
        for par_dir,_,files in g:
            for file in files:
                file_abs_path=r'%s\%s'%(par_dir,file)
              #  print('file_abs_path is ==>: ',file_abs_path)
                target.send(file_abs_path)
#g=search()

#d=r'D:\code\py\py3\Coursepy'
#g.send(d)

@init
def opener(target):
    while True:
        file_abs_path=yield
      #  print('opener==>: ',file_abs_path)
        with open(file_abs_path,encoding='utf-8') as f:
            target.send((file_abs_path,f))
        #    pass
#o=opener()
#o.__next__
#o.send('/2.py')
#g=search(opener())   # 将opener函数传送给search   直接在search函数里直接打开
#g.send(d)   测试发送文件打开

@init
def cat(target):
    '''遍历文件内容'''
    while True:
        file_abs_path,f=yield
        for line in f:
            #print(line)
           # print('file_abs_path & line : ',file_abs_path,line)
            target.send((file_abs_path,line))
@init
def grep(target,pattern):
    while True:
        file_abs_path,line=yield
        if pattern in line:
            target.send(file_abs_path)
@init
def printer():
    while True:
        file_abs_path=yield
        print(file_abs_path)

#将文件路径发送给函数
xx=r'D:\code\py\py3\Coursepy\L05\a\b\b'
x=r'D:\code\py\py3\Coursepy\L05\a'
gg=search(opener(cat(grep(printer(),'python'))))
#print(gg)
gg.send(x)



扩展  添加了标志位  防止出现一个文件中多行包含内容 出现多次打印文件名的问题

示例见:

https://github.com/5StevenWu/Coursepy/blob/master/L05/%E8%A1%A8%E8%BE%BE%E5%BC%8Fyield%E7%9A%84%E7%94%A8%E9%80%942.py

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值