3

I have logs in my syslog file on ubuntu. Can I watch a new messages to it from python or I always need to open/close my syslog file? Thanks

user2928288
  • 51
  • 2
  • 3

1 Answers1

5

This is how you would do it (using generators):

import time

def follow(syslog_file):
    syslog_file.seek(0,2) # Go to the end of the file
    while True:
        line = syslog_file.readline()
        if not line:
            time.sleep(0.1) # Sleep briefly
            continue
        yield line

It works like 'tail -f'. The code was taken from here: http://www.dabeaz.com/generators/Generators.pdf (page 39). Also, a similar SO question:

Read from a log file as it's being written using python

Michele
  • 2,796
  • 2
  • 21
  • 29
mpaf
  • 6,597
  • 6
  • 38
  • 42