Skip to content

Instantly share code, notes, and snippets.

@jseidl
Last active May 11, 2018 21:15
Show Gist options
  • Save jseidl/ecc4e6468943149f23f4 to your computer and use it in GitHub Desktop.
Save jseidl/ecc4e6468943149f23f4 to your computer and use it in GitHub Desktop.
Simple persistent "tail -f" in pure python
#!/usr/bin/env python
import sys, sqlite3, time, os
FILENAME = sys.argv[1]
SINCEDB_NAME = '.sincedb'
conn = sqlite3.connect(SINCEDB_NAME)
c = conn.cursor()
# Check if table exists. if not, creates it
table_check = c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='pointers'")
if table_check.fetchone() is None:
print "Pointers table not found, creating."
c.execute("CREATE TABLE pointers ('filename' TEXT NOT NULL, 'pointer' INTEGER NOT NULL)")
conn.commit()
c.execute('SELECT pointer FROM pointers WHERE filename = ?', (FILENAME,))
ret = c.fetchone()
if ret is None:
pointer = 0
else:
pointer = int(ret[0])
try:
while True:
size = os.stat(FILENAME).st_size
if size > pointer:
h = open(FILENAME, 'r')
h.seek(pointer)
for line in h:
print line.strip('\n')
h.close()
pointer = size
c.execute('INSERT OR REPLACE INTO pointers (filename, pointer) VALUES (?, ?)', (FILENAME, pointer))
conn.commit()
else:
time.sleep(1)
except KeyboardInterrupt:
sys.exit(0)
except Exception:
pass # non-ideal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment