Python vs bash stderr stdout 缓冲
Python vs bash stderr stdout buffering
如何让我的 python 脚本在 stderr 和 stdout 缓冲方面表现得像 bash? Bash 正在缓冲 stderr 和 stdout,以便打印的消息按时间顺序显示。下面的示例脚本说明了该行为。在 Ubuntu 14.04.
上使用 Python 2.7 进行测试
cstderr.c
#include <stdio.h>
#include <stdlib.h>
main()
{
fprintf(stderr, "C out to stderr\n");
exit(0);
}
bash_stderr.sh
echo Before C cstderr
./cstderr.out
echo After C cstderr
py_stderr.py
#!/usr/bin/env python
import subprocess
print("Before C cstderr")
subprocess.check_call("./cstderr.out")
print("After C cstderr")
Bash 行为
$ ./bash_stderr.sh > outfile 2>&1
$ cat outfile
Before C cstderr
C out to stderr
After C cstderr
Python 行为
$ ./py_stderr.py > outfile 2>&1
$ cat outfile
C out to stderr
Before C cstderr
After C cstderr
Bash 在执行任何外部程序之前刷新标准输出。 Python 没有。要获得所需的行为,请在 subprocess.check_call()
.
之前立即调用 sys.stdout.flush()
在 python 的 miscellaneous options 部分中查找 -u
选项。它强制标准输入、输出和错误不被缓冲,因此不需要刷新。
对于我的 Ubuntu 4.2.0-42-generic 系统上的 Python 2 和 3,即使没有 -u
选项。
如何让我的 python 脚本在 stderr 和 stdout 缓冲方面表现得像 bash? Bash 正在缓冲 stderr 和 stdout,以便打印的消息按时间顺序显示。下面的示例脚本说明了该行为。在 Ubuntu 14.04.
上使用 Python 2.7 进行测试cstderr.c
#include <stdio.h>
#include <stdlib.h>
main()
{
fprintf(stderr, "C out to stderr\n");
exit(0);
}
bash_stderr.sh
echo Before C cstderr
./cstderr.out
echo After C cstderr
py_stderr.py
#!/usr/bin/env python
import subprocess
print("Before C cstderr")
subprocess.check_call("./cstderr.out")
print("After C cstderr")
Bash 行为
$ ./bash_stderr.sh > outfile 2>&1
$ cat outfile
Before C cstderr
C out to stderr
After C cstderr
Python 行为
$ ./py_stderr.py > outfile 2>&1
$ cat outfile
C out to stderr
Before C cstderr
After C cstderr
Bash 在执行任何外部程序之前刷新标准输出。 Python 没有。要获得所需的行为,请在 subprocess.check_call()
.
sys.stdout.flush()
在 python 的 miscellaneous options 部分中查找 -u
选项。它强制标准输入、输出和错误不被缓冲,因此不需要刷新。
对于我的 Ubuntu 4.2.0-42-generic 系统上的 Python 2 和 3,即使没有 -u
选项。