Skip to main content
 首页 » 编程设计

python之我如何将数据发送到另一个程序并得到它的答案

2025年04月02日8sharpest

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

比如我有这样的C++程序:

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

并且想像这样使用 python 检查它:

good = True 
 
for a in range(10): 
    for b in range(10): 
        input = str(a) + " " + str(b) 
        output, exitcode = run("cpp_pow.exe", input)   <--- 
        if exitcode != 0: 
            print("runtime error on", input) 
            print("exitcode =", exitcode) 
            good = False 
            break 
        r = a ** b 
        if output != r: 
            print("wrong answer on", input) 
            print(output, "instead of", r) 
            good = False 
            break 
    if not good: 
        break 
 
if good: 
    print("OK") 

最简单的方法是什么?


附言可能在 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 

请您参考如下方法:

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

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