输入到 C++ 可执行文件 python 子进程

input to C++ executable python subprocess

我有一个 C++ 可执行文件,其中包含以下代码行

/* Do some calculations */
.
.
for (int i=0; i<someNumber; i++){
   int inputData;
   std::cin >> inputData;
   std::cout<<"The data sent from Python is :: "<<inputData<<std::endl;
   .
   .
   /* Do some more calculations with inputData */
}

这是在循环中调用的。我想在 python 子进程中调用此可执行文件,例如

p = Popen(['./executable'], shell=True, stdout=PIPE, stderr=PIPE, stdin=PIPE)

我可以使用

从可执行文件中获取输出
p.server.stdout.read()

但我无法使用

从 python 发送数据(整数)
p.stdin.write(b'35')

因为cin是在循环中调用的,所以stdin.write也应该被调用多次(在循环中)。以上可能吗..?

有什么提示和建议吗? 提前致谢。

这里是如何从 Python 调用 C++ 可执行文件并从 Python 与其通信的简单示例。

1) 请注意,在写入子进程的输入流(即 stdin)时必须添加 \n(就像如果 运行 您会点击 Rtn程序手动)。

2) 还要注意流的刷新,这样接收程序就不会在打印结果之前等待整个缓冲区填满而卡住。

3) 如果 运行 Python 3,请务必将流值从字符串转换为字节(参见 )。

Python:

from subprocess import Popen, PIPE

p = Popen(['a.out'], shell=True, stdout=PIPE, stdin=PIPE)
for ii in range(10):
    value = str(ii) + '\n'
    #value = bytes(value, 'UTF-8')  # Needed in Python 3.
    p.stdin.write(value)
    p.stdin.flush()
    result = p.stdout.readline().strip()
    print(result)

C++:

#include <iostream>

int main(){
    for( int ii=0; ii<10; ++ii ){
        int input;
        std::cin >> input;
        std::cout << input*2 << std::endl;
        std::cout.flush();
    }
}

运行Python的输出:

0
2
4
6
8
10
12
14
16
18