python3實(shí)現(xiàn)tailf命令的示例代碼
由于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}標(biāo)識(shí)分割后的第一個(gè)元素占位,依次遞增。",
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
例子:
輸出內(nèi)容:python3 tailf.py app.log
按照分隔符分割并按照指定格式輸出:python3 tailf.py app.log -F "|" -s "第一列:{0} 第二列:{1}"
輸出匹配內(nèi)容:python3 tailf.py app.log -g 匹配字符
按照分隔符分割并按照指定格式的匹配內(nèi)容輸出:python3 tailf.py app.log -F "|" -s "第一列:{0} 第二列:{1}" -g 匹配字符
補(bǔ):python實(shí)現(xiàn)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()到此這篇關(guān)于python3實(shí)現(xiàn)tailf命令的示例代碼的文章就介紹到這了,更多相關(guān)python3 tailf命令內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python數(shù)據(jù)分析之使用scikit-learn構(gòu)建模型
這篇文章主要介紹了Python數(shù)據(jù)分析之使用scikit-learn構(gòu)建模型,sklearn提供了model_selection模型選擇模塊、preprocessing數(shù)據(jù)預(yù)處理模塊、decompisition特征分解模塊,更多相關(guān)內(nèi)容需要朋友可以參考下面文章內(nèi)容2022-08-08
python 將dicom圖片轉(zhuǎn)換成jpg圖片的實(shí)例
今天小編就為大家分享一篇python 將dicom圖片轉(zhuǎn)換成jpg圖片的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-01-01
Python?GUI實(shí)現(xiàn)PDF轉(zhuǎn)Word功能
這篇文章主要介紹了如何使用?wxPython?創(chuàng)建一個(gè)簡單的圖形用戶界面(GUI)應(yīng)用程序,結(jié)合?pdf2docx?庫,實(shí)現(xiàn)將?PDF?轉(zhuǎn)換為?Word?文檔的功能,需要的可以參考下2024-12-12

