Original story: [tail -f in Python] (http://qiita.com/sakamotomsh/items/f1cc47010a90e1e790fb)
[Like tail in Python] (http://blog.liris.org/2010/01/pythontail.html) I don't think it's that hard.
Recently I saw an article that watchdog is useful.
I tried using this for file monitoring. To make it OS independent [PollingObserver] It seems to use (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()
In each terminal do the following:
$ vm_stat -c 60 0.3 >> logs/vmstat.log
$ python tail-f.py logs/vmstat.log
Recommended Posts