【问题标题】:input to C++ executable python subprocess输入到 C++ 可执行 python 子进程
【发布时间】:2015-09-14 16:58:02
【问题描述】:

我有一个 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 也应该被多次调用(在循环中)。这上面可能吗..?

任何提示和建议我该怎么做? 提前致谢。

【问题讨论】:

  • omg ...我希望您的计算非常昂贵,否则这可能在 python 中执行或仅在 C 中执行可能更快...如果它们很昂贵,您应该考虑将 c++ 编译成一个 dll 甚至是一个 python 库......(如果可以的话,当然可以将用户输入从 c 代码中取出)
  • @JoranBeasley 是的,我在 python 中的计算成本很高。这就是我选择这样做的原因。我还需要用 python 交流小数据。

标签: python c++ subprocess popen cin


【解决方案1】:

以下是如何从 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

【讨论】:

  • 非常感谢您的帮助。但不幸的是我收到错误说TypeError: 'str' does not support the buffer interface ....
  • @AdityaG 只需更改为 p.stdin.write(b'35\n') ... 使用 bytes 而不是 str (@Velimir 正在使用 str ,可能是不同的 python 版本)
  • @Joran Beasley,你是对的。 AdityaG,您必须运行 Python 3。在这种情况下,您必须将字符串转换为字节。我添加了一条评论。
  • @Velimir ... 还有一个小问题,你认为我们可以发送这样的 numpy 数组吗? (我会尝试但只是好奇)。
  • 好吧,使用这种方法,您可以从 Python 流式传输任何您想要的内容,只要您的 C++ 可执行文件正确解析标准输入。但理想情况下,您可以直接在 Python 中调用您的 C++ 计算例程,方法是包装您的 C++ 代码(例如使用 SWIG)并生成 Python 可调用函数——创建子进程和流式字节并不是最佳的。
猜你喜欢
  • 2015-01-06
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-29
  • 2019-08-26
相关资源
最近更新 更多