Pythonでtail --follow=name

· python, tail

※ この記事は 14 年以上前に書かれたものです。

Pythonでログをtailして1行ずつ処理したいと思ったんだけど、じゃあtailコマンドの結果を受け取ればいいんじゃねっていうプログラムです。

#!/usr/bin/env python

import subprocess

filename = 'test.log'
cmd = ('tail -n +1 --follow=name ' + filename)
p = subprocess.Popen([cmd], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
  print  p.stdout.readline()

tailf.py (Gist)

-n +1で一行目から読み込みます。

読み込みつつ、ポジションファイルとか作って何行目まで読んだとか保存しておけば、後でリカバリできます。

まぁ、Pythonで全部書けばいいじゃんて思うかもしれませんが、こういうやり方もあるよっていうことで。