我已经阅读了许多与此有关的问题,并学到了很多,但我仍然无法解决我的问题。我正在构建一个运行C++可执行文件的wxPython应用程序,并实时显示该可执行文件的stdout。我遇到了几个奇怪的结果,试图使这项工作。这里是我的当前设置/问题:Python从子流程捕获标准输出逐行
//test.cc (compiled as test.out with gcc 4.5.2)
#include <stdio.h>
int main()
{
FILE* fh = fopen("output.txt", "w");
for (int i = 0; i < 10000; i++)
{
printf("Outputting: %d\n", i);
fprintf(fh, "Outputting: %d\n", i);
}
fclose(fh);
return 0;
}
#wxPythonScript.py (running on 2.7 interpreter)
def run(self):
self.externalBinary = subprocess.Popen(['./test.out'], shell=False, stdout=subprocess.PIPE)
while not self.wantAbort:
line = self.externalBinary.stdout.readline()
wx.PostEvent(self.notifyWindow, Result_Event(line, Result_Event.EVT_STDOUT_ID))
print('Subprocess still running')
print('Subprocess aborted smoothly')
如果我运行上面的代码的子进程需要很长的时间才能完成,即使所有它需要做的就是写出来的数据并退出。但是,如果我运行下面的它很快就结束了:
#wxPythonScript.py (running on 2.7 interpreter)
def run(self):
outFile = open('output.txt', 'r+')
self.externalBinary = subprocess.Popen(['./test.out'], shell=False, stdout=outFile)
while not self.wantAbort:
#line = self.externalBinary.stdout.readline()
#wx.PostEvent(self.notifyWindow, Result_Event(line, Result_Event.EVT_STDOUT_ID))
print('Subprocess still running')
print('Subprocess aborted smoothly')
所以基本上每当我从子到管道标准输出重定向它会减慢/挂起,但如果我把它写入一个文件,或不把它重定向完全没问题。这是为什么?
请搜索。这经常被问到。 –
可能的重复[读取子进程标准输出行](http://stackoverflow.com/questions/2804543/read-subprocess-stdout-line-by-line) –
我做过承诺。我读过一吨。 2天前,我对子进程,线程,wx事件,stdout一无所知。我会继续寻找当然。你能推荐一些关键字来搜索吗?也许我在寻找错误的东西。大多数我搜查:非阻塞stdout.readline python,子进程标准输出等 – anderspitman