ibezito
ibezito

Reputation: 5822

returning several outputs from c++ application

I'm writing a c++ program which evaluates the result of 3 values.

I would like call this application by a python script, which should receive these values.

The problem is that c++ main function, returns one integer value only.

What's the best approach to solve this issue?

Thanks!

Upvotes: 0

Views: 57

Answers (1)

Paul Rooney
Paul Rooney

Reputation: 21609

You could save the intermediate values in a file or you could write to stdout in the c++ code e.g.

#include <iostream>

int main()
{
    std::cout << "param1,param2,param3\n";
}

Now in python use subprocess.Popen to execute the c++ code and capture stdout using a PIPE.

from subprocess import Popen, PIPE

process = Popen('./nameofyourexe', stdout=PIPE, stderr=PIPE)

output, err = process.communicate()

if process.returncode == 0:
    print(output.decode().strip().split(','))
else:
    print('error: %s' % err.decode())

It's up to you in which format you output the three parameters. I put them all on the same line, separated by commas and simply split in the python code. You may choose to do it differently, depending upon your needs.

After compiling the c++ and running the python from the same directory. The output is

['param1', 'param2', 'param3']

Note:

I used './nameofyourexe' (prefix with ./) to execute the program from the current directory. This may not work on windows (I'm on linux) or if you execute it from a different directory than the current one. To get around this you could pass the cwd parameter to Popen specifying the directory containing the exe.

Upvotes: 2

Related Questions