【发布时间】:2015-03-25 18:48:34
【问题描述】:
我正在尝试使用 Python 来捕获这个编译后的 C 程序的输出:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main() {
srand(time(NULL));
do {
int r = rand();
printf("%s\t%d\n", "my.key", r);
usleep(100000);
} while ( 1 );
}
如果我运行以下命令,我会看到我的二进制输出与我预期的 python 输出交错(因为 stdout/stderr 不是 subprocess.PIPE,self.output 和 self.error 是 None)。
self.process = Popen(shlex.split(self.path_to_binary), stdout=sys.stdout, stderr=sys.stderr);
self.output, self.error = self.process.communicate();
但是,如果我将 stdout 和 stderr 参数更改为 subprocess.PIPE,subprocess.communicate() 仍然无法捕获 self.output 或 self.error 中的任何内容。
self.process = Popen(shlex.split(self.path_to_binary), stdout=subprocess.PIPE, stderr=subprocess.PIPE);
self.output, self.error = self.process.communicate();
相同的 sn-p 代码将捕获 bash 脚本的输出:
#!/bin/bash
while true ; do
printf "%s\t%s\n" "my.key" "$RANDOM"
usleep 100000
done
两个脚本都不会自然退出 - 大约三秒钟后它们都被 self.process.kill() 杀死。
为什么 Python 可以捕获 bash 输出而不能捕获二进制输出?我可以在等式的 Python 方面做些什么来捕获二进制文件的输出,无需修改 C 源代码?
【问题讨论】:
-
首先,用
fflush(stdout);在你的C程序中flush outout。
标签: python c linux bash python-2.7