logs – 当使用文件记录器时,stderr在stdout之前刷新

我的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")

当我运行代码为python a.py时,它显示,

i am a daemon
i will be run using nohup
i am an error message inside nohup process

当我运行代码为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

使用nohup时,为什么在stdout日志之前刷新/写入stderr日志?

解决方法:

我不认为这与nohup有什么关系.当你执行python a.py>时,你会得到相同的行为. a.log 2>& 1.

Python最有可能在下面使用C文件stdio.有了它,stdout在终端时将进行行缓冲,并在stdout是文件时进行缓冲. stderr总是无缓冲的.

将stdout重定向到文件会将stdout的缓冲从line-buffered切换到buffered并导致打印的字符串卡在缓冲区中,只有在程序(流)关闭时才会刷新. stderr流使文件更快,因为它是无缓冲的.

您可以使用stdbuf来调整标准缓冲,强制行以正确的顺序打印:

stdbuf -o0 python a.py  >a.log 2>&1
上一篇:CentOS7中安装Rocket时 nohup sh bin/mqbroker -n localhost:9876 & 启动broker失败


下一篇:如何在关闭SSH后继续在后台运行进程