2016-11-06 58 views
2

我想要一个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") 

什么是最简单的方法是什么?


P.S.可能更容易在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 
+1

也许你可以使用[特使(https://github.com/kennethreitz/envoy)? – Olian04

+0

你看过** subprocess **模块吗? –

+0

@ Olian04,我如何在Windows上安装它? – Pavel

回答

1

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

只需更换与字面字节的字符串文字('')(b''

相关问题