Skip to content

Instantly share code, notes, and snippets.

@hhatto
Created June 2, 2012 15:55
Show Gist options
  • Save hhatto/2858922 to your computer and use it in GitHub Desktop.
Save hhatto/2858922 to your computer and use it in GitHub Desktop.
tail -f when multi file
import sys
import os
import time
MAX_INTERVAL = 1.0
class Poller:
def __init__(self, files):
self.kv = {}
self.now = None
for filename in files:
_f = open(filename)
_f.read()
stat = os.stat(filename)
self.kv[filename] = {'file': _f, 'position': _f.seek(stat[6])}
def run_forever(self):
while True:
for obj in self.kv:
fp = self.kv[obj]['file']
where = fp.tell()
lines = fp.readlines()
if not lines:
fp.seek(where)
time.sleep(MAX_INTERVAL)
else:
if self.now != fp.name:
print "\n==> %s <==" % fp.name
self.now = fp.name
print "".join(lines),
if __name__ == "__main__":
p = Poller(sys.argv[1:])
try:
p.run_forever()
except KeyboardInterrupt:
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment