当使用&将Python脚本放在后台运行时,Nohup不起作用。

12

在这里,最基本的问题是我想在Linux上使用nohup运行一个简单的Python脚本。我使用以下命令来运行它(在Linux上):

nohup python test.py &

这个命令似乎没有任何作用,在 nohup.out 中没有任何内容被追加。如果我在不加 & 的情况下运行它,输出会正确显示在终端窗口上。我错过了什么吗?

import time

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

if __name__ == "__main__":
    test()
4个回答

29

为了不缓冲标准输出,可以在python中使用-u标志。

nohup python -u test.py &

否则Python会缓冲标准输出。这不需要更改代码。

来自手册页面:

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

1
我在使用nohup运行Python脚本时遇到了问题,但现在已经解决了。非常感谢。 - Joels Elf

4
您需要在打印后刷新stdoutsys.stdout.flush();否则它会花费一些时间来填充stdout缓冲区。

3

我曾经遇到过类似的问题。当不使用nohup时,我的脚本能够正常工作。但是在使用nohup时,脚本会崩溃并显示SyntaxError。

问题出在nohup执行上下文中别名python映射到了python2,而不是python3

通过指定python3而不是python来解决了这个问题。


你是救命恩人!!!非常感谢你:) - Kavindu Vindika

1
我遇到了同样的问题,但我的算法比你演示的要复杂一些。我已经创建了一个Python虚拟环境,并安装了所有必要的包以供执行。只有在激活虚拟环境后,它才能正常运行:source env/bin/activate。激活环境后,我可以正常运行,没有任何错误:nohup python3 -u scriptShow.py > logScriptNohup.log &
如果您想确保它正在运行,请在终端中输入:ps aux | grep scriptShow。如果出现正在运行的进程,恭喜您,您做到了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接