亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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命令內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 用Python遠程登陸服務器的步驟

    用Python遠程登陸服務器的步驟

    這篇文章主要介紹了用Python遠程登陸服務器的步驟,幫助大家更好的理解和學習使用python,感興趣的朋友可以了解下
    2021-04-04
  • Python數據分析之使用scikit-learn構建模型

    Python數據分析之使用scikit-learn構建模型

    這篇文章主要介紹了Python數據分析之使用scikit-learn構建模型,sklearn提供了model_selection模型選擇模塊、preprocessing數據預處理模塊、decompisition特征分解模塊,更多相關內容需要朋友可以參考下面文章內容
    2022-08-08
  • Python參數的傳遞幾種情況實例詳解

    Python參數的傳遞幾種情況實例詳解

    這篇文章主要給大家介紹了關于Python參數的傳遞的相關資料,在Python中傳遞參數指的是函數或方法中的參數傳輸方式,文中給出了詳細的代碼示例,需要的朋友可以參考下
    2023-09-09
  • Python optparse模塊及簡單使用

    Python optparse模塊及簡單使用

    optparse,是一個更夠讓程序設計人員輕松設計出簡單明了、易于使用、符合標準的Unix命令例程式的Python模塊,生成使用和幫助信息,這篇文章主要介紹了Python optparse模塊簡單使用,需要的朋友可以參考下
    2022-12-12
  • 基于Python繪制個人足跡地圖

    基于Python繪制個人足跡地圖

    這篇文章主要介紹了基于Python繪制個人足跡地圖,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-06-06
  • Pycharm最常用的快捷鍵及使用技巧

    Pycharm最常用的快捷鍵及使用技巧

    這篇文章主要介紹了Pycharm常用的快捷鍵及使用技巧,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-03-03
  • NumPy 矩陣乘法的實現示例

    NumPy 矩陣乘法的實現示例

    這篇文章主要介紹了NumPy 矩陣乘法的實現示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-03-03
  • python 將dicom圖片轉換成jpg圖片的實例

    python 將dicom圖片轉換成jpg圖片的實例

    今天小編就為大家分享一篇python 將dicom圖片轉換成jpg圖片的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • Python?GUI實現PDF轉Word功能

    Python?GUI實現PDF轉Word功能

    這篇文章主要介紹了如何使用?wxPython?創(chuàng)建一個簡單的圖形用戶界面(GUI)應用程序,結合?pdf2docx?庫,實現將?PDF?轉換為?Word?文檔的功能,需要的可以參考下
    2024-12-12
  • pandas獲取對應的行或者列方式

    pandas獲取對應的行或者列方式

    這篇文章主要介紹了pandas獲取對應的行或者列方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-02-02

最新評論