当 运行 在后台使用 & 时,Python 脚本的 Nohup 不工作

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

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

nohup python test.py &

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

import time

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

if __name__ == "__main__":
    test()

打印后需要冲洗stdoutsys.stdout.flush();否则需要一段时间来填充标准输出缓冲区。

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

刚刚遇到了类似的问题。我的脚本在没有 nohup 的情况下运行良好。使用 nohup,脚本会因 SyntaxError 而崩溃。

问题出在 nohup 的执行上下文,它将使用别名 python 映射到 python2 而不是 python3

通过指定 python3 而不是 python 来修复它。