![](/img/trans.png)
[英]How to capture streaming output in python from subprocess.communicate()
[英]Python subprocess.communicate() does not capture output from simple binary
我正在嘗試使用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 );
}
如果我運行下面,我看到從我的二進制交錯的輸出與我的蟒蛇輸出作為我希望(和自標准輸出/標准錯誤都沒有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();
相同的代碼片段將捕獲bash腳本的輸出:
#!/bin/bash
while true ; do
printf "%s\t%s\n" "my.key" "$RANDOM"
usleep 100000
done
這兩個腳本都不自然退出-大約三秒鍾后,它們都通過self.process.kill()
被殺死。
為什么Python可以捕獲bash輸出而不捕獲二進制輸出? 我可以在方程式的Python端執行任何操作來捕獲二進制文件的輸出, 而無需修改C源代碼 ?
輸出正在緩沖:
您需要從c刷新:
int main() {
srand(time(NULL));
do {
int r = rand();
printf("%s\t%d\n", "my.key", r);
usleep(100000);
fflush(stdout);
} while ( 1 );
}
並遍歷stdout.readline, communicate
正在等待過程完成,因此您將不會獲得任何輸出:
for line in iter(p.stdout.readline,""):
print(line)
如果您希望輸出不緩沖而不更改c代碼,則可以在Linux上使用stdbuf :
p = Popen(["stdbuf","-oL","binary"], stdout=PIPE, stderr=PIPE)
for line in iter(p.stdout.readline,""):
print(line)
-oL
將被行緩沖。
for line in iter(p.stdout.readline,"")
使用for line in iter(p.stdout.readline,"")
不更改c代碼的情況下for line in iter(p.stdout.readline,"")
但是輸出將被緩沖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.