<p>如何使python脚本在stderr和stdout缓冲方面表现得像bash?Bash正在缓冲stderr和stdout,以便按时间顺序显示打印的消息。下面的示例脚本说明了该行为。在Ubuntu14.04上用Python2.7测试。在</p>
<h2>cstderr.c.公司</h2>
<pre><code>#include <stdio.h>
#include <stdlib.h>
main()
{
fprintf(stderr, "C out to stderr\n");
exit(0);
}
</code></pre>
<h2>巴什_标准格式在</h2>
^{2}$
<h2>是的_stderr.py公司在</h2>
<pre><code>#!/usr/bin/env python
import subprocess
print("Before C cstderr")
subprocess.check_call("./cstderr.out")
print("After C cstderr")
</code></pre>
<h2>重击行为</h2>
<pre><code>$ ./bash_stderr.sh > outfile 2>&1
$ cat outfile
Before C cstderr
C out to stderr
After C cstderr
</code></pre>
<h2>Python行为</h2>
<pre><code>$ ./py_stderr.py > outfile 2>&1
$ cat outfile
C out to stderr
Before C cstderr
After C cstderr
</code></pre>