Search code examples
pythonc++testingio

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?


Solution

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