How to use Python to input to and get output from C++ program?

Viewed 1933

I'm currently trying to automate the testing of a C++ program which takes input from the terminal and outputs the result onto the terminal. For example my C++ file would do something like below:

#include <iostream>

int main() {
    int a, b;
    std::cin >> a >> b;
    std::cout << a + b;
}

And my Python file used for testing would be like:

as = [1, 2, 3, 4, 5]
bs = [2, 3, 1, 4, 5]
results = []

for i in range(5):
    # input a[i] and b[i] into the C++ program
    # append answer from C++ program into results

Although it is possible to input and output from C++ through file I/O, I'd rather leave the C++ program untouched.

What can I do instead of the commented out lines in the Python program?

5 Answers

You could use subprocess.Popen. Sample code:

#include <iostream>

int sum(int a, int b) {
    return a + b;
}


int main ()
{
    int a, b;

    std::cin >> a >> b;
    std::cout << sum(a, b) << std::endl;
    
}
from subprocess import Popen, PIPE

program_path = "/home/user/sum_prog"

p = Popen([program_path], stdout=PIPE, stdin=PIPE)
p.stdin.write(b"1\n")
p.stdin.write(b"2\n")
p.stdin.flush()

result = p.stdout.readline().strip()
assert result == b"3"
python_program.py | cpp_program

On the command line will feed the standard output of python_program.py into the standard input of cpp_program.

This works for all executables, no matter what programming language they are written in.

You can use supproccess for getting data from called program, example for whois:

import subprocess
proc = subprocess.Popen(['whois', 'google.com'], stdout=subprocess.PIPE)
data = proc.communicate()[0]
print( data )
Related