Nohup for Python脚本在后台运行时无法正常运行&

时间:2015-08-25 20:35:31

标签: python linux nohup

归结为最小的问题是一个简单的python脚本,我想在linux上使用nohup运行。我使用以下(在Linux上)运行它:

nohup python test.py &

该命令似乎没有做任何事情,没有任何内容附加到nohup.out。如果我没有&运行它输出在终端窗口上正确显示。我错过了什么?

import time

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

if __name__ == "__main__":
    test()

1 个答案:

答案 0 :(得分:10)

将python -u标志传递给unbuffering stdout

nohup python -u test.py &

否则Python将缓冲stdout。这并不需要更改代码。

从手册页:

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