1

test.py (work):

import time

_, a, b = [1, 2, 3]
print a
print b

run the code: python test.py > test.log

you will get the log in test.log

test.py (not work):

import time

_, a, b = [1, 2, 3]
print a
print b

while True:
    time.sleep(5)

But this one you get None in the log.

How do I get log before the program finished, without the python log module(just use the redirect '>')?

Levi
  • 175
  • 1
  • 2
  • 13
  • Lookup "flush output". I marked your question as a duplicate of another one. Though it said "screen" and not file, it's actually the same thing from your program's perspective. – spectras Jun 15 '16 at 05:40
  • `import sys; sys.stdout.flush()` – Torxed Jun 15 '16 at 05:43
  • the fifth answer is worked for file,but not accepted in that question. – Levi Jun 15 '16 at 05:48

1 Answers1

3

Python buffers stdout by default so the log gets written to disk in chunks. You can turn off the buffering a few different ways, here are two. You can use the -u option when you call the script, ie:

python -u test.py

You can use the enviornment varialbe PYTHONUNBUFFERED:

export PYTHONUNBUFFERED=true
python test.py
Bi Rico
  • 25,283
  • 3
  • 52
  • 75