python3实现tailf命令的示例代码

 更新时间:2023年11月24日 11:27:14   作者: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命令内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python实现程序判断季节的代码示例

    Python实现程序判断季节的代码示例

    今天小编就为大家分享一篇关于Python实现程序判断季节的代码示例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • Python3的进程和线程你了解吗

    Python3的进程和线程你了解吗

    这篇文章主要为大家详细介绍了Python3进程和线程,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-03-03
  • 教你用Python实现一个轮盘抽奖小游戏

    教你用Python实现一个轮盘抽奖小游戏

    Python提供了许多个图像开发界面的库,比如现在主流的Tkinter,wxPython,pyqt5等,三种各有优点,也各有缺点,下面对其分别进行介绍和对比,并编写代码实现一个轮盘转盘抽奖小游戏.需要的朋友可以参考下
    2021-05-05
  • Python中re.findall()用法详解

    Python中re.findall()用法详解

    本文主要介绍了Python中re.findall()用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • Python实现数据清洗的18种方法

    Python实现数据清洗的18种方法

    本文主要介绍了Python实现数据清洗的18种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2025-01-01
  • Python可视化学习之seaborn绘制矩阵图详解

    Python可视化学习之seaborn绘制矩阵图详解

    矩阵图即用一张图绘制多个变量之间的关系,数据挖掘中常用于初期数据探索。本文介绍python中seaborn.pairplot和seaborn.PairGrid绘制矩阵图,需要的可以参考一下
    2022-02-02
  • Django后端分离 使用element-ui文件上传方式

    Django后端分离 使用element-ui文件上传方式

    这篇文章主要介绍了Django后端分离 使用element-ui文件上传方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-07-07
  • Django项目打包完整步骤以及可能出现的问题

    Django项目打包完整步骤以及可能出现的问题

    django项目的结构大体上都是类似,打包主要的功能就是把一些不需要部署的文件剔除,把需要部署的文件直接压缩打包,下面这篇文章主要给大家介绍了关于Django项目打包完整步骤以及可能出现问题的相关资料,需要的朋友可以参考下
    2023-06-06
  • Python爬虫工具requests-html使用解析

    Python爬虫工具requests-html使用解析

    这篇文章主要介绍了Python爬虫工具requests-html使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • 超详细注释之OpenCV制作图像Mask

    超详细注释之OpenCV制作图像Mask

    这篇文章主要介绍了OpenCV制作图像Mask,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-09-09

最新评论