0

I have a simple python program, sample.py:

import time
n = 1
while True:
    print 'Testing', n
    n += 1
    time.sleep (1)

When I run the program in bash as a background job:

$ python sample.py &> sample.log &

Now watch the log file:

$ watch tail -n5 sample.log

I don't see anything unless the program is stopped. Also, if view the sample.log file in any text editor, its empty.

So, how can I view the changes in the log file in real-time?

Debdut
  • 129
  • 1
  • 8

1 Answers1

2

Output gets buffered; flush the buffer after each print, and you'll see your watch command produce the expected output.

import time
import sys

n = 1
while True:
    print 'Testing', n
    sys.stdout.flush()
    n += 1
    time.sleep (1)
Prune
  • 76,765
  • 14
  • 60
  • 81