Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 860
George Tian Avatar asked Nov 16 '25 17:11

George Tian


1 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"
like image 148
alex_noname Avatar answered Nov 18 '25 05:11

alex_noname



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!