Pavel Pavel - 1 year ago 84
Python Question

How do I send data to another program and get its answer?

I want a python script which will launch another program, send to it some input and get its output.

For example, I have such C++ program:

#include <iostream>

class BigInt {

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

And want to check it using python like this:

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
r = a ** b
if output != r:
print("wrong answer on", input)
print(output, "instead of", r)
good = False
if not good:

if good:

What is the easiest way to do this?

P.S. May be it is easier to write same program on python:

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

And compare their answers on many inputs via PowerShell?

Edit: I've tried to read output using

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

but it doesn't work and I couldn't fix th error:

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

Answer Source

To fix the error with the subprocess module, send bytes to the application, as the .communicate method doesn't accept strings to input.

Simply replace the string literal ('') with a bytes literal (b'')

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download