Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to find a nice way to read a log file in real time using python. I'd like to process lines from a log file one at a time as it is written. Somehow I need to keep trying to read the file until it is created and then continue to process lines until I terminate the process. Is there an appropriate way to do this? Thanks.

like image 991
Anon Avatar asked Jul 20 '10 13:07

Anon


People also ask

How can I tail a log file in Python?

To tail a log file in Python, we can run tail with the sh module. We call tail with the file name and _iter set to True to let us run an infinite loop and print out line which has the output.

Can Python read and write files?

One of the most common tasks that you can do with Python is reading and writing files. Whether it's writing to a simple text file, reading a complicated server log, or even analyzing raw byte data, all of these situations require reading or writing a file.


2 Answers

Take a look at this PDF starting at page 38, ~slide I-77 and you'll find all the info you need. Of course the rest of the slides are amazing, too, but those specifically deal with your issue:

import time def follow(thefile):     thefile.seek(0,2) # Go to the end of the file     while True:         line = thefile.readline()         if not line:             time.sleep(0.1) # Sleep briefly             continue         yield line 
like image 173
Wayne Werner Avatar answered Oct 14 '22 17:10

Wayne Werner


You could try with something like this:

import time  while 1:     where = file.tell()     line = file.readline()     if not line:         time.sleep(1)         file.seek(where)     else:         print line, # already has newline 

Example was extracted from here.

like image 20
Pablo Santa Cruz Avatar answered Oct 14 '22 17:10

Pablo Santa Cruz