George Tian
George Tian

Reputation: 441

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?

Upvotes: 4

Views: 4538

Answers (5)

alex_noname
alex_noname

Reputation: 32153

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"

Upvotes: 4

Zaiborg
Zaiborg

Reputation: 2522

You will need to use pythons subprocess module (https://docs.python.org/2/library/subprocess.html) to start your compiled C++ application and send in your variables and read the output of the subprocess using Popen.communicate() (https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate).

Example code might look like:

import subprocess
p = subprocess.Popen(["cpp_app", stdin=subprocess.PIPE,stdout=subprocess.PIPE)
out, _ = p.communicate(b"1 2")
print(out, err)

Upvotes: 0

iqmaker
iqmaker

Reputation: 2262

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 )

Upvotes: 0

Andreas Vinter-Hviid
Andreas Vinter-Hviid

Reputation: 1482

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.

Upvotes: 2

Luis Bote
Luis Bote

Reputation: 169

You can comunicate it by .txt Write txt with your matrix and read it on Python, 2 programms cant use same memory.

Else use Cython and code your C++ on Python https://github.com/cythonbook/examples/tree/master/07-wrapping-c/01-wrapping-c-functions-mt-random

Upvotes: 0

Related Questions