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

Adi*_*yaG 3 c++ python subprocess popen cin

我有一个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 */
}
Run Code Online (Sandbox Code Playgroud)

这是在循环中调用的.我想在python子进程中调用这个可执行文件

p = Popen(['./executable'], shell=True, stdout=PIPE, stderr=PIPE, stdin=PIPE)
Run Code Online (Sandbox Code Playgroud)

我可以使用来自可执行文件的输出

p.server.stdout.read()
Run Code Online (Sandbox Code Playgroud)

但我无法使用python发送数据(整数)

p.stdin.write(b'35')
Run Code Online (Sandbox Code Playgroud)

由于 cin在循环中调用,stdin.write因此也应该多次调用(在循环中).以上是否可能..?

任何提示和建议我怎么能这样做?提前致谢.

Vel*_*ker 9

这是如何从Python调用C++可执行文件并从Python进行通信的简约示例.

1)请注意,\n在写入stdin子流程的输入流(即)时必须添加(就像Rtn手动运行程序时一样).

2)还要注意刷新流,以便在打印结果之前,接收程序不会等待整个缓冲区填满.

3)如果运行Python 3,请确保将流值从字符串转换为字节(请参阅/sf/answers/382994601/).

蟒蛇:

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)
Run Code Online (Sandbox Code Playgroud)

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

运行Python的输出:

0
2
4
6
8
10
12
14
16
18
Run Code Online (Sandbox Code Playgroud)