我有一个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
也应该多次调用(在循环中)。这有可能吗?
有什么提示和建议吗? 提前谢谢。
这是如何从Python调用C++可执行文件的一个极简示例,并用Python与之通信。
1)请注意,在写入子进程的输入流(即
stdin
)时,必须添加\n
(就像手动运行程序时会单击Rtn
)。2)还要注意流的刷新,这样接收程序在打印结果之前就不会在等待整个缓冲区填满时卡住。
3)如果运行Python 3,请确保将流值从字符串转换为字节(请参见https://stackoverflow.com/a/5471351/1510289)。
Python:
<强> C++:
运行Python的输出:
相关问题 更多 >
编程相关推荐