11

I have a simple python script that just runs an infinite while loop and prints "running". When I start it up with nohup in the background, I see a nohup.out file in my current directory but nothing ever gets written to it. I am confused. I have tried the following

nohup test.py 

writes to nohup.out but obviously does not run in the background

nohup test.py &

runs in background but does not write to nohup.out

nohup test.py 2>&1 &

also runs in the background but does not write to nohup.out

I bet I am missing something simple. Any ideas?

Here is my python script for reference:

import sys
from time import sleep

def main():
    print "Starting...."
    while True:
        print "running..."
        sleep(5.00)


if __name__ == "__main__":
     main()
Deep Kapadia
  • 1,468
  • 8
  • 21

2 Answers2

23

Maybe your stdout is not flushed immediately, because it is not attached to a terminal. Try using

import sys
sys.stdout.flush()

to flush your output.

In python3 you can use flush=True as an argument to the print function to do that.

print("running...", flush=True)
Karl Bartel
  • 3,244
  • 1
  • 29
  • 28
  • This is almost certainly the case. If you take out the `sleep(5.00)` then you overwhelm the buffer and the system flushes for you. This is a generic case, and not specific to Python either. – Mei Dec 16 '11 at 17:02
  • @Mei it is very specific to Python. I was very surprise to get empty nohup file. I've never seen this before with java or bash script. – ACV Jun 09 '21 at 21:48
2

The short answer is to use nohup python -u args... to force python to print and flush buffer for each print() call.

I believe this is due to Python's default behaviour to write to buffer first, but nohup doesn't trigger the buffer to be cleared.

More specific answers can be found here at https://superuser.com/questions/764479/force-output-buffer-flush-in-running-program.

Chuan
  • 429
  • 5
  • 16