C++可执行Python子过程的输入

2024-09-28 21:14:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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()

但是我不能使用

p.stdin.write(b'35')

由于cin是在循环中调用的,因此stdin.write也应该多次调用(在循环中)。这有可能吗?

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


Tags: 代码可执行文件forstdinstdoutsomedowrite
1条回答
网友
1楼 · 发布于 2024-09-28 21:14:36

这是如何从Python调用C++可执行文件的一个极简示例,并用Python与之通信。

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

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

3)如果运行Python 3,请确保将流值从字符串转换为字节(请参见https://stackoverflow.com/a/5471351/1510289)。

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

相关问题 更多 >