如何使python脚本在stderr和stdout缓冲方面表现得像bash?Bash正在缓冲stderr和stdout,以便按时间顺序显示打印的消息。下面的示例脚本说明了该行为。在Ubuntu14.04上用Python2.7测试。在
#include <stdio.h>
#include <stdlib.h>
main()
{
fprintf(stderr, "C out to stderr\n");
exit(0);
}
#!/usr/bin/env python
import subprocess
print("Before C cstderr")
subprocess.check_call("./cstderr.out")
print("After C cstderr")
$ ./bash_stderr.sh > outfile 2>&1
$ cat outfile
Before C cstderr
C out to stderr
After C cstderr
$ ./py_stderr.py > outfile 2>&1
$ cat outfile
C out to stderr
Before C cstderr
After C cstderr
在python的miscellaneous options部分中查找
-u
选项。它强制标准输入、输出和错误无缓冲,因此不需要刷新。在不管怎样,即使没有
-u
选项,在我的ubuntu4.2.0-42-generic系统上,您的程序似乎可以正常工作而不需要修改python2和python3。在Bash在执行任何外部程序之前刷新stdout。Python没有。要获得所需的行为,请在
subprocess.check_call()
之前立即调用sys.stdout.flush()
。在相关问题 更多 >
编程相关推荐