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

问题描述 投票:2回答:2

归结为这里最小的问题是一个简单的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()
python linux nohup
2个回答
11
投票

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

4
投票

你需要在打印后冲洗stdoutsys.stdout.flush();否则填充stdout缓冲区需要一段时间。

© www.soinside.com 2019 - 2024. All rights reserved.