0

I have a python script running on startup in the background. Its print commands do not come through to the bash console as they do when calling the script manually with e.g. python script.py. Output and errors can be redirected to file by calling python script.py > log.txt 2>&1. But after startup, as the script runs, I can see the log file but it has zero size, so is presumably waiting for the script to end. Calling it with cat returns nothing. I've tried using append >> instead with no luck.

Is there any way to make the output happen in real time, so it can be viewed?

geotheory
  • 22,624
  • 29
  • 119
  • 196
  • 2
    Be sure to [flush the output](http://stackoverflow.com/q/230751/478288) to make sure buffering isn't the culprit. – chrisaycock Nov 06 '15 at 23:37
  • Use stderr to log - it's not buffered. See http://stackoverflow.com/questions/15860372/in-python-can-i-redirect-the-output-of-print-function-to-stderr – Andrew Henle Nov 06 '15 at 23:41
  • @chrisaycock is right that inserting `sys.stdout.flush()` into the code fixes it. Any strong views on which method is optimal? – geotheory Nov 06 '15 at 23:44
  • 2
    They're basically the same. It just calls `flush()` internally for you in the stderr case. – Barmar Nov 07 '15 at 00:01
  • @chrisaycock welcome to submit as answer, or I can if you prefer? – geotheory Nov 07 '15 at 08:34

1 Answers1

0

Your output is being buffered, so flush it inside the Python script to ensure the results will appear:

sys.stdout.flush()
Community
  • 1
  • 1
chrisaycock
  • 36,470
  • 14
  • 88
  • 125