Python与bash stderr stdout缓冲

2024-06-26 13:27:30 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使python脚本在stderr和stdout缓冲方面表现得像bash?Bash正在缓冲stderr和stdout,以便按时间顺序显示打印的消息。下面的示例脚本说明了该行为。在Ubuntu14.04上用Python2.7测试。在

cstderr.c.公司

#include <stdio.h>
#include <stdlib.h>
main()
{
    fprintf(stderr, "C out to stderr\n");
    exit(0);
}

巴什_标准格式在

^{2}$

是的_stderr.py公司在

#!/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

Python行为

$ ./py_stderr.py > outfile 2>&1
$ cat outfile 
C out to stderr
Before C cstderr
After C cstderr

Tags: topy脚本bashincludestderrstdout公司
2条回答

在python的miscellaneous options部分中查找-u选项。它强制标准输入、输出和错误无缓冲,因此不需要刷新。在

不管怎样,即使没有-u选项,在我的ubuntu4.2.0-42-generic系统上,您的程序似乎可以正常工作而不需要修改python2和python3。在

Bash在执行任何外部程序之前刷新stdout。Python没有。要获得所需的行为,请在subprocess.check_call()之前立即调用sys.stdout.flush()。在

相关问题 更多 >