我有一个问题一直困扰着我,但似乎找不到解决办法。我一直使用subprocess.Popen()来访问一个进行重计算的C++应用程序,但是它在Popen().stdout.read()处经常会卡死。 以下是Python代码:
process = subprocess.Popen(['/path/to/my/executable'], shell=False,
stdout=subprocess.PIPE, stdin=subprocess.PIPE)
process.stdin.write("Some String")
print process.stdout.read()#It freezes here
以下是 C++ 代码:
int main(int argc, char** argv) {
...Prep work...
while (1) {
string input;
cin>>input;
...Some Work ...
cout<< response;
}
}
这段 C++ 代码在 shell 中能够完美运行,但是我不知道为什么在 Python 上会出现卡顿的情况。
process.stdin
被缓存,你的写入可能不会立即显示在 C++ 程序中。同样地,如果process.stdout
被缓存,C++ 的写入也可能不会立即显示在你的 Python 程序中。 - chepnerprint process.stdout.readline()
会怎样?并确保您的C ++代码在打印到cout
时附加换行符。 - Praetorian