c++ - 子进程卡住 popen().stdout.read

标签 c++ python subprocess ipc cout

这个问题困扰了我一段时间,我似乎找不到解决方案,我一直在使用 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 上卡住

最佳答案

改用communicate():

import subprocess
process = subprocess.Popen(['app'], shell=False,
                           stdout=subprocess.PIPE,
                           stdin=subprocess.PIPE)
out, err = process.communicate("Some String")
print out

此外,请确保在某个时刻结束您的 C++ 进程。例如,当您到达输入流的末尾时:

#include <string>
#include <iostream>
using namespace std;

int main(int argc, char** argv) {
    //...Prep work...
    while (cin) {  // <-- Will eventually reach the end of the input stream
        string input;
        cin >> input;
        //...Some Work ...
        string response = input;
        cout << response;
    }
}

在python的文档中对此有一个警告: http://docs.python.org/2/library/subprocess.html#subprocess.Popen.stdin (右上)

它解释了当您写入外部应用程序时,数据可能会放入队列中。此外,您的外部应用程序的输出也可能会放入队列中。 communicate() 将“刷新”您发送到外部应用程序的内容并等待您的应用程序终止。

使用 communicate() 将在内存中获取整个外部应用程序的输出。如果不切实际(例如巨大的输出),您可以使用 stdin 和 stdout 对象进行写入或读取。你需要注意不要“死锁”:

import subprocess

process = subprocess.Popen(['app'], shell=False,
                           stdout=subprocess.PIPE,
                           stdin=subprocess.PIPE)
process.stdin.write("Some String")
process.stdin.close()  # <-- Makes sure the external app gets an EOF while
                       #     reading its input stream.
for line in process.stdout.readlines():
    print line

但即使使用这种技术,也要确保您提供给外部应用程序的输入足够小,以避免在写入时发生阻塞。

如果您的输入也很大,则必须确保您的读取和写入没有阻塞。那么使用线程很可能是一个不错的选择。

关于c++ - 子进程卡住 popen().stdout.read,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17198441/

相关文章:

c++ - 无法使用 GLEW 在 openGL 中绘制任何内容(mac、c++)

C++ 自定义异常 : run time performance and passing exceptions from C++ to C (as error info)

python - Azure DevOps 使用 Python API 添加注释

python - 递归字典创建python

python - 如何将二维 numpy 数组与结构化数组合并

Python 子进程因 TypeError : bufsize must be an integer 而失败

c++ - 为什么这个总工资函数返回 0?

c++ - 合理的压缩 block 大小

python - 如何使用 python 将代理设置/凭据传递到命令提示符,以便同一 python 代码中的后续命令可以访问互联网?

python - 在python命令行输入python命令