python3实现tailf命令的示例代码
作者:testqa_cn
本文主要介绍了python3实现tailf命令的示例代码,tail -f 是一个linux的操作命令.其主要的是会把文件里的最尾部的内容显显示在屏幕上,并且不断刷新,只要文件有变动就可以看到最新的文件内容,感兴趣的可以了解一下
由于windows上面没有类似linux上面的tailf命令,所以下面的python脚本来代替其能力。
tailf.py
import re
import time
import os
import argparse
def follow(thefile):
thefile.seek(0, os.SEEK_END)
while True:
_line = thefile.readline()
if not _line:
time.sleep(0.1)
continue
yield _line
class Pipe(object):
def handle(self, _line):
pass
class AwkPipe(Pipe):
def __init__(self, fs, script):
self.fs = fs
self.script = script
def 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_str
def handle(self, _line):
if re.search(grep, _line):
return _line
return None
class 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.grep
pipes = []
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:
continue
for pipe in pipes:
_tmp_line = pipe.handle(_tmp_line)
if _tmp_line is None:
break
except 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 匹配字符
补:python实现tail -f命令功能
#!/usr/bin/env python
#!encoding:utf-8
'''
Python-Tail - Unix tail follow implementation in Python.
python-tail can be used to monitor changes to a file.
Example:
import tail
# Create a tail instance
t = tail.Tail('file-to-be-followed')
# Register a callback function to be called when a new line is found in the followed file.
# If no callback function is registerd, new lines would be printed to standard out.
t.register_callback(callback_function)
# Follow the file with 5 seconds as sleep time between iterations.
# If sleep time is not provided 1 second is used as the default time.
t.follow(s=5) '''
# Author - Kasun Herath <kasunh01 at gmail.com>
# Source - https://github.com/kasun/python-tail
import os
import sys
import time
class Tail(object):
''' Represents a tail command. '''
def __init__(self, tailed_file):
''' Initiate a Tail instance.
Check for file validity, assigns callback function to standard out.
Arguments:
tailed_file - File to be followed. '''
self.check_file_validity(tailed_file)
self.tailed_file = tailed_file
self.callback = sys.stdout.write
def follow(self, s=1):
''' Do a tail follow. If a callback function is registered it is called with every new line.
Else printed to standard out.
Arguments:
s - Number of seconds to wait between each iteration; Defaults to 1. '''
with open(self.tailed_file) as file_:
# Go to the end of file
file_.seek(0,2)
while True:
curr_position = file_.tell()
line = file_.readline()
if not line:
file_.seek(curr_position)
else:
self.callback(line)
time.sleep(s)
def register_callback(self, func):
''' Overrides default callback function to provided function. '''
self.callback = func
def check_file_validity(self, file_):
''' Check whether the a given file exists, readable and is a file '''
if not os.access(file_, os.F_OK):
raise TailError("File '%s' does not exist" % (file_))
if not os.access(file_, os.R_OK):
raise TailError("File '%s' not readable" % (file_))
if os.path.isdir(file_):
raise TailError("File '%s' is a directory" % (file_))
class TailError(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return self.message
if __name__=='__main__':
args = sys.argv
if len(args)<2:
print 'need one filename parameter'
exit(1)
t = Tail(args[1])
#t.register_callback(print_line)
t.follow()到此这篇关于python3实现tailf命令的示例代码的文章就介绍到这了,更多相关python3 tailf命令内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
