zoukankan      html  css  js  c++  java
  • Python学习笔记7:yield生成迭代器

    yield生成迭代器

    yield生成迭代器是将一个函数通过yield方法将其转化为迭代器,其中yield后面的值为迭代器每执行一次next返回的值

    使用迭代器模仿Linux终端中 tail -f filename.txt |grep 'error' |grep '404'命令

    import time
    
    
    # 读取文件每一行,使用yield程序制作为迭代器
    def tail(file_path):
        with open(file_path, 'r', encoding='utf-8') as f:
            f.seek(0, 1)  # 将文件指针指向最后一个
            
            # 让文件死循环,不断读取新增内容
            while True:
                line = f.readline()
                
                # 如果line非空,说明是新内容,返回
                if line:
                    yield line 
                # 如果为空,说明没有新内容,这是为了降低循环次数沉睡1秒
                else:
                    time.sleep(1)
    
    
    # 遍历lines中的每一行中是否含有string,将其作为第二个迭代器
    def grep(lines, string):
        # 遍历lines迭代器
        for each_line in lines:
            if string in each_line:
                yield each_line
                
    
    path = '123.txt'
    t = tail(path)
    s = '404'
    g = grep(t, s)
    
    for i in g:
        print(i)
  • 相关阅读:
    ZooKeeperACL机制
    windows结束端口对应的进程
    facenet模型训练
    sourcetree git合并问题
    人脸识别学习
    爬虫 第八天
    WCF nginx反向代理遇到的问题
    WPF WindowChrome 自定义窗口
    WPF svg 转 xmal
    WPF MVVM笔记
  • 原文地址:https://www.cnblogs.com/rendawei/p/7051141.html
Copyright © 2011-2022 走看看