我的python代码:
import sys
print "i am a daemon"
print "i will be run using nohup"
sys.stderr.write("i am an error message inside nohup process\n")
Run Code Online (Sandbox Code Playgroud)
当我运行代码时python a.py,它显示,
i am a daemon
i will be run using nohup
i am an error message inside nohup process
Run Code Online (Sandbox Code Playgroud)
当我运行代码时nohup python a.py > a.log 2>&1 < /dev/null &,a.log 显示,
i am an error message inside nohup process
i am a daemon
i will be run using nohup
Run Code Online (Sandbox Code Playgroud)
为什么在使用时 stderr 日志会在 stdout 日志之前被刷新/写入nohup?
我不认为这与nohup. 当你这样做时,你会得到相同的行为python a.py > a.log 2>&1。
Python 很可能在下面使用 C 文件 stdio。这样,stdout当在终端中时,将被行缓冲,并在stdout是文件时被缓冲。stderr总是无缓冲的。
重定向stdout到文件会将stdout的缓冲从行缓冲切换到缓冲,并导致printed 字符串卡在缓冲区中,只有在程序(流)关闭时才会刷新。该stderr流使得其对文件更快,因为它的缓冲。
您可以使用stdbuf调整标准缓冲,强制行以正确的顺序打印:
stdbuf -o0 python a.py >a.log 2>&1
Run Code Online (Sandbox Code Playgroud)