Nohup for Python script not working when running in the background with &

You need to flush stdout after printing: sys.stdout.flush(); otherwise it'll take awhile to fill the stdout buffer.


Pass python the -u flag for unbuffering stdout

nohup python -u test.py &

Python will buffer stdout otherwise. This doesn't require a code change.

From the man page:

       -u     Force  stdin,  stdout and stderr to be totally unbuffered.  On systems where it matters, also put stdin, stdout
          and stderr in binary mode.  Note that there is internal buffering in xreadlines(), readlines() and  file-object
          iterators ("for line in sys.stdin") which is not influenced by this option.  To work around this, you will want
          to use "sys.stdin.readline()" inside a "while 1:" loop.

Just had a similar issue. My script worked well without nohup. With nohup, the script would crash with a SyntaxError.

The problem was the execution context of nohup which would use an alias of python mapped to python2 instead of python3.

Fixed it by specifying python3 instead of python.