Can I use file.readline in a blocking manner? Am I doing this right?
I'm trying to write a something that monitors a log file and add开发者_Go百科s a timestamp when it sees a complete line:
import sys
f = open(sys.argv[1])
if not f:
print 'Failed to open %s' % sys.argv[1]
print sys.argv[1]
import time
try:
while True:
line = f.readline().replace('\n', '')
if not line:
continue
print time.time(), line
except KeyboardInterrupt:
pass
f.close()
The check for line contents is there because, to my surprise, readlines does not block, but rather returns an empty string for the end of file immediately.
So then, for monitoring files, I have a few questions: Is there any way I can set this to block? I'm seeing empty strings in this loop, is there any chance they don't actually represent an end of line? Do files that are still opened for writing have end of line characters added to them?
- Test file size with
os.path.getsize
to see if there is a difference in the file f.readline
only if there is a difference in size- Every time you read call
seek
first to make sure you are actually reading the last line. - Use
f.readline()[0:-1]
to get rid of the trailing\n
(thanks to rm for pointing out thatrstrip
might cause you problems) - Instead of running this loop constantly, test once a second and use
sleep
(Trust me, your computer will thank you)
you can open tail
like program using subprocess and read its output which will block e.g. here is a quick python tail
import time
from subprocess import Popen, PIPE
file_path = '/home/auniyal/src/main/app.log'
p = Popen(['tail', '-f', file_path], stdout=PIPE)
while True:
line = p.stdout.readline()
print time.time(),"Wow",line
精彩评论