我有一个 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,请务必将流值从字符串转换为字节(参见 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
关于python - 输入到 C++ 可执行 python 子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32570029/