How Come I Can't Tail My Log?
In my python script, I have this: count = 0 while 1: print count count += 1 I saved this file and I ran it. nohup python count.py >> test.log & $tail -f test.lo
Solution 1:
When you redirect Python output, the stdout
stream is opened in buffered mode (instead of line-buffered mode). This means that output is kept in memory until enough lines have been printed before flushing the buffer.
To see lines immediately, you need to flush the output stream:
import sys
count = 0while1:
print count
sys.stdout.flush()
count += 1
Alternatively, use the -u
command line switch to force unbuffered I/O:
nohup python -u count.py >> test.log &
or you can use the PYTHONUNBUFFERED
environment variable:
PYTHONUNBUFFERED=1 nohup python count.py >> test.log &
or re-open the stdout
filehandle in unbuffered mode:
import os
import sys
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
In Python 3.3 and up this is all a little simpler; you simply tell print()
to flush:
print(count, flush=True)
Solution 2:
It's because writes to standard output are buffered by default. You will see nothing until the buffer fills up or the file descriptor is flushed or closed.
Post a Comment for "How Come I Can't Tail My Log?"