python3通过生成器实现动态获取日志

tail -f命令能够显示文件的实时动态更新,方便日志跟踪,今天用python3写了一个类似的小程序 python3通过生成器实现动态获取日志 - 1

实现过程:

  1. 程序首先判断用户执行本程序时是否附带参数
    • 假如不附带参数或附带参数大于2,则打印程序help内容
  2. 获取到文件路径后,执行tail函数,tail不断循环检测文件是否有新的内容增加,如果有则返回新曾的行,如果没有就进入下一次循环
  3. 主程序部分获取到tail函数返回的可迭代对象,通过for进行遍历输出新内容

具体实现


#!/bin/python3
# -*- coding:utf-8 -*-
''' dynamic get file new content '''
import sys,time
#functions
def tail(file_path):
    ''' file_path -> line '''
    with open(file_path,'r') as file_read:
        file_read.seek(0, 2) #goto file bottom
        while True:
            line = file_read.readline() #readline from user input file
            if line:
                yield line #return line
            time.sleep(0.5)
#main program
def main():
    if len(sys.argv) == 2: #get arg from user input
        file_flush = tail(sys.argv[1]) #get file new line
        for line in file_flush:
            print(line,end='') #print line no enter            
    else:
        print("python3 tail.py [file]") #print help
#program entry
if __name__ == "__main__":
    main()

额外小程序


除了tail -f,甚至可以尝试把cat和grep整合在一起,非常适合练手的一个小程序,包含了系统传参、文件处理、吧啦吧啦的语句

#!/bin/python3
# -*- coding:utf-8 -*-
import os,sys
#functions
def grep(str1,file_contents):
    for line in file_contents:
        if str1 in line:
            yield line
def cat(file_path):
    with open(file_path,'r') as file_read:
        for line in file_read:
            yield line
#main program
def main():
    if len(sys.argv) == 3:
        if os.path.exists(sys.argv[2]):
            file_contents = cat(sys.argv[2])
            grep_contents = grep(sys.argv[1], file_contents)
            for x in grep_contents:
                print(x,end='')
        else:
            print("file not exist.")
    else:
        print("python3 cat.py [grepcontent] [file]") #print help
#program entry
if __name__ == '__main__':
    main()

Leave a Reply

Your email address will not be published. Required fields are marked *