Python: yield与协程

本文介绍了一个使用Python协程实现的文件搜索系统。该系统能够递归地搜索指定目录下的所有匹配模式的文件,并能处理常见的压缩文件格式。此外,还实现了文件内容过滤功能,可以查找包含特定字符串的文件。

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


1.没有显示结果是怎么回事?
import os,fnmatch
@coroutine
def find_files(target):
    while True:
        topdir,pattern=(yield)
        for path,dirname,filelist in os.walk(topdir):
            for name in filelist:
                if fnmatch.fnmatch(name,pattern):
                    target.send(os.path.join(path,name))
import gzip,bz2
@coroutine
def opener(target):
    while True:
        name=(yield )
        if name.endwith('.gz'): f=gzip.open(name)
        elif name.endwith('.bz2'): f=bz2.BZ2File(name)
        else:f=open(name)
        target.send(f)

@coroutine
def cat(target):
    while True:
        f=(yield)
        for line in f:
            target.send(line)

@coroutine
def grep(pattern,target):
    while True:
        line=yield
        if pattern in line:
            target.send(line)
import sys
@coroutine
def printer():
    while True:
        line=yield
        sys.stdout.write(line)
finder=find_files(opener(cat(grep('python',printer()))))
finder.send(('www','access-log'))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值