Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
            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")

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 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)

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

  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
like image 302
Pavel Avatar asked Apr 14 '26 13:04

Pavel


1 Answers

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'')

like image 94
illright Avatar answered Apr 17 '26 01:04

illright



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!