22
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python で tail -f っぽいもの

Last updated at Posted at 2015-02-03

元ネタ: [Python で tail -f]
(http://qiita.com/sakamotomsh/items/f1cc47010a90e1e790fb)

[Pythonでtailもどき]
(http://blog.liris.org/2010/01/pythontail.html) を見てもそんな大変じゃないと思う。

最近 watchdog が便利だという記事を見かけました。

これをファイル監視に使いながらやってみました。
OS 非依存にするには [PollingObserver]
(http://pythonhosted.org//watchdog/api.html#module-watchdog.observers.polling) を使うようです。

tail-f.py
#!/usr/bin/env python
import os
import sys
import time
from os.path import dirname, exists

from watchdog.events import FileSystemEventHandler
from watchdog.observers.polling import PollingObserver


class TailHandler(FileSystemEventHandler):

    def __init__(self, path):
        self.path = path
        self.file = open(path, 'r')
        self.pos = os.stat(path)[6]

    def close(self):
        self.file.close()

    def print_line(self):
        self.file.seek(self.pos)
        for block in iter(lambda: self.file.read(32), ''):
            print(block, end='')
        self.pos = self.file.tell()

    def on_modified(self, event):
        if event.is_directory or self.path != event.src_path:
            return
        self.print_line()


def tail_like(path):
    observer = PollingObserver()
    handler = TailHandler(path)
    observer.schedule(handler, dirname(path))
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    finally:
        handler.close()
    observer.join()


def main():
    path = sys.argv[1]
    if not exists(path):
        print('{} is not found'.format(path))
        return 
    tail_like(path)


if __name__ == '__main__':
    main()

それぞれのターミナルで以下を実行する。

$ vm_stat -c 60 0.3 >> logs/vmstat.log
$ python tail-f.py logs/vmstat.log
22
21
1

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
22
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?