由于windows上面没有类似linux上面的tailf命令,所以下面的python脚本来代替其能力。
tailf.py
import re
import timeimport os
import argparsedef follow(thefile):thefile.seek(0, os.SEEK_END)while True:_line = thefile.readline()if not _line:time.sleep(0.1)continueyield _lineclass Pipe(object):def handle(self, _line):passclass AwkPipe(Pipe):def __init__(self, fs, script):self.fs = fsself.script = scriptdef handle(self, _line: str):clos = _line.split(self.fs)try:return self.script.format(*clos)except IndexError as e:return "parse_err:" + self.script + str(clos)class GrepPipe(Pipe):def __init__(self, grep_str):self.grep_str = grep_strdef handle(self, _line):if re.search(grep, _line):return _linereturn Noneclass PrintPipe(Pipe):def handle(self, _line):if _line.endswith("\n"):print(_line, end="")else:print(_line)if __name__ == '__main__':arg_parser = argparse.ArgumentParser()arg_parser.add_argument("file")arg_parser.add_argument("-F", help="分隔符", required=False)arg_parser.add_argument("-s", help="脚本,使用format的{0}格式,{0}标识分割后的第一个元素占位,依次递增。",required=False)arg_parser.add_argument("-g", "--grep", help="过滤字符,支持正则", required=False)args = arg_parser.parse_args()logfile = open(args.file, "r", encoding='utf-8')grep = args.greppipes = []if args.F and args.s:pipes.append(AwkPipe(args.F, args.s))if grep:pipes.append(GrepPipe(grep))pipes.append(PrintPipe())try:loglines = follow(logfile)for line in loglines:_tmp_line = line.strip()if not _tmp_line:continuefor pipe in pipes:_tmp_line = pipe.handle(_tmp_line)if _tmp_line is None:breakexcept KeyboardInterrupt:pass
例子:
输出内容:python3 tailf.py app.log
按照分隔符分割并按照指定格式输出:python3 tailf.py app.log -F "|" -s "第一列:{0} 第二列:{1}"
输出匹配内容:python3 tailf.py app.log -g 匹配字符
按照分隔符分割并按照指定格式的匹配内容输出:python3 tailf.py app.log -F "|" -s "第一列:{0} 第二列:{1}" -g 匹配字符