Reputation: 271924
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.log
Nothing shows up when I tail it.
Upvotes: 0
Views: 937
Reputation: 1122342
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 = 0
while 1:
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)
Upvotes: 8
Reputation: 29625
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.
Upvotes: 0