python 实时显示文件变更

Posted on Posted in python

python 实时显示文件

方法一

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#

import subprocess
import time

logFile1 = '1.log'
logFile2 = '2.log'
# 监控 1.log ,10秒,再监控 2.log
def monitorLog(logFile):
    print("The monitor file is %s" % logFile)
    stoptime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time() + 10))
    print(stoptime)
    popen = subprocess.Popen('tail -f ' + logFile, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    pid = popen.pid
    print('Popen pid: ' + str(pid))
    while True:
        line = popen.stdout.readline().strip()
        if line:
            print(line)
        thistime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        if thistime >= stoptime:
            popen.kill()
            print('kill pid %s' % pid)
            break
    time.sleep(1)
    monitorLog(logFile2)
    
if __name__ == "__main__":
    monitorLog(logFile1)

方法二

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#

import time

fileLog = open('1.log')

while 1:
    where = fileLog.tell()
    line = fileLog.readline().strip()
    if not line:
        time.sleep(1)
        fileLog.seek(where)
    else:
        print(line)

方法三

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#

import time

def follow(thefile):
    thefile.seek(0,2)
    while True:
        line = thefile.readline()
        if not line:
            time.sleep(0.1)
            continue
        yield line
if __name__ == "__main__":
    logfile = open("1.log","r")
    loglines = follow(logfile)
    for line in loglines:
        print(line,)

方法四

github kasun/python-tail 上摘录

tail.py

#!/usr/bin/env python

'''
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)
                    time.sleep(s)
                else:
                    self.callback(line)

    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

example.py

#!/usr/bin/env python

''' 
python-tail example.
Does a tail follow against /var/log/syslog with a time interval of 5 seconds.
Prints recieved new lines to standard out '''

import tail

def print_line(txt):
    ''' Prints received text '''
    print(txt)

t = tail.Tail('/home/lhh/pro/ilog/1.log')
t.register_callback(print_line)
t.follow(s=5)

setup.py

# !/usr/bin/env python

from distutils.core import setup

setup(name='python-tail',
    description='Unix Tail follow implementation',
    author='Kasun Herath',
    author_email='kasunh01@gmail.com',
    py_modules=['tail'],
    )
» 转载请注明来源:若我若鱼 » python 实时显示文件变更

Leave a Reply

Your email address will not be published. Required fields are marked *

eighteen + 7 =