Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Boiling down to the smallest problem here is a simple python script that I want to run using nohup on linux. I run it using the following (on linux):

nohup python test.py &

The command seems to just not do anything, nothing is appended to nohup.out. If I run it without the & the output shows correctly on the terminal window. What am I missing?

import time

def test():
    while(True):
      print "Woke up!"
      time.sleep(5)

if __name__ == "__main__":
    test()
like image 748
user2399453 Avatar asked Aug 25 '15 20:08

user2399453


2 Answers

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.
like image 52
Metropolis Avatar answered Sep 25 '22 11:09

Metropolis


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

like image 20
Dan D. Avatar answered Sep 25 '22 11:09

Dan D.