Basically I was looking for a way to read from a file that is being constantly written to in Python, e.g. log file.
I found this: https://stackoverflow.com/a/5420116/10638608
And the answer is:
import time
def follow(thefile):
thefile.seek(0,2)
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
yield line
if __name__ == '__main__':
logfile = open("run/foo/access-log","r")
loglines = follow(logfile)
for line in loglines:
print line,
I started asking myself why does it work. I mean okay, theoretically, seeking to the end, waiting till the line comes up, reading it and printing it - pretty simple, right? But why is it possible that two processes operate on the same file, one writes to it (and closes it), one reads from it, and the thefile
handle is not corrupted in any way and is able to read next line from the file? Wouldn't this be a critical section of some sort?