grep -rl 'python' /root

本文介绍了一种利用Python协程来实现类似grep命令的方法,该方法能够在指定目录下搜索包含特定字符串的所有文件路径,并通过一系列自定义协程处理文件读取、内容过滤等任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# grep -rl 'python' /root  搜索root目录下文件内容包含python的文件名路径
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)
                target.send(file_abs_path)


@init
def opener(target):
    while True:
        file_abs_path = yield
        with open(file_abs_path,'r',encoding='utf-8') as f:
            target.send((file_abs_path,f))


@init
def cat(target):
    while True:
        file_abs_path,f = yield
        for line in f:
            tag =target.send((file_abs_path,line))   #注意:对于需要传两个yield的,在send时需要将这两个值放在一个元组中传递(())
            if tag:
                break

@init
def grep(target,pattern):
    tag = False
    while True:
        file_abs_path,line = yield tag
        tag = False
        if pattern in line:
            tag = True
            target.send(file_abs_path)

@init
def printer():
    while True:
        file_abs_path = yield
        print(file_abs_path)

#调用
x = r'D:\Python_OldBoy\课程\day5\day5\a'
g = search(opener(cat(grep(printer(),'python'))))
g=  search(opener(cat(grep(printer(),'python'))))
g.send(x)

  

转载于:https://www.cnblogs.com/wangkc/p/6938913.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值