LoginSignup
16
18

More than 5 years have passed since last update.

ログ監視スクリプト

Posted at

linuxには、tail -fという便利なコマンドがあります。os.statというものがあるというのを今日知ったのでちょこっとソースを書いてみた。引数から渡されたファイルを監視するようにしています。ファイルの末尾への移動、現在のファイルポインタの位置の取得方法、ファイルからのデータの読み出し方法だけで実現しています。
※久しぶりにpython触りました。

sample.py
#-*- coding: utf-8 -*-
import time
import os
import sys
from stat import *

def usage():
    print "Usage: # python %s filename" % argv[0]
    quit()


def init(filename):
    file = open(filename,'r')

    #ファイル末尾へ移動
    st_results = os.stat(filename)
    st_size = st_results[ST_SIZE]
    file.seek(st_size)

    return file

def tail_f(file, usec):
    msec = usec / 1000
    while 1:
        fpos = file.tell()
        line = file.readline()
        if not line:
            time.sleep(msec)
            file.seek(fpos)
        else:
            print line,
    # 未到達
    file.close()
    pass

if __name__ == '__main__':
    argv  = sys.argv
    argc  = len(argv)
    if( argc != 2 ):
        usage()

    filename = argv[1]
    file = init(filename)
    tail_f(file, 500)

ちなみにlinuxでしか使わないのであれば、tail -fのラッパースクリプトにしちゃうという手もありですね。

sample.py
import sys
import os

if __name__ == '__main__':
    argv = sys.argv
    argc = len(argv)

    if argc != 2:
        print "test",
        quit()

    filename = argv[1]
    os.system('tail -f ' + filename )
16
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
18