2016-11-06 55 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''

相關問題