Answer a question

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()

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.
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐