如何将数据发送到另一个程序并获得其答案?

2024-04-27 18:09:32 发布

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

我想要一个python脚本,它将启动另一个程序,向它发送一些输入并获得其输出。在

例如,我有这样的C++程序:

#include <iostream>

class BigInt {
    ...
}

int main() {
    BigInt a, b;
    std::cin >> a >> b;
    std::cout << a.pow(b);
}

想用python检查一下:

^{pr2}$

最简单的方法是什么?在


另外,在python上编写相同的程序可能更容易:

a, b = map(int, input().split())
print(a ** b)

通过PowerShell比较他们的答案?在



编辑:我尝试使用subprocess读取输出:

from subprocess import Popen, PIPE
p = Popen('p.exe', stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdoutdata, stderrdata = p.communicate(input='2 1 1 2')
print(stdoutdata)

但它不起作用,我也无法修复这个错误:

  File "test.py", line 3, in <module>
    stdoutdata, stderrdata = p.communicate(input='2 10')
  File "c:\Python33\lib\subprocess.py", line 922, in communicate
    stdout, stderr = self._communicate(input, endtime, timeout)
  File "c:\Python33\lib\subprocess.py", line 1196, in _communicate
    self.stdin.write(input)
TypeError: 'str' does not support the buffer interface

Tags: inpy程序inputlinefileintsubprocess
1条回答
网友
1楼 · 发布于 2024-04-27 18:09:32

要修复subprocess模块的错误,请向应用程序发送字节,因为.communicate方法不接受要输入的字符串。在

只需将字符串文本('')替换为字节文本(b''

相关问题 更多 >