JbGT
JbGT

Reputation: 125

Send value back from c++ to python

I guess my problem is fairly straight-forward, however I can't find a way to solve it. My process is the following:

  1. I run a Python script: Test.py.
  2. Within that script, I am calling a c++ program.

Test.py:

RunCprogram = "./Example"
os.system(RunCprogram)

I want that ./Example executable to return a double that can be used later in my Python script. What is the best way to do that?

Upvotes: 3

Views: 586

Answers (2)

dlavila
dlavila

Reputation: 1212

Here's a small example based on @ForceBru answer:

example.cpp, compile with g++ example.cpp -o example

#include <iostream>

int main() {
    std::cout << 3.14159 ;
    return 0;
}

example.py

#!/usr/local/bin/python

import subprocess

res = subprocess.check_output(["./example"], universal_newlines=True)

print "The value of 2*" + u"\u03C0" + " is approximately " + str(2*float(res))

Upvotes: 2

ForceBru
ForceBru

Reputation: 44858

First of all, make sure Example outputs the desired data to stdout. If it's not, you can do nothing about it.

Then use the Python's subprocess module.

import subprocess

res=subprocess.check_output(["./Example"], universal_newlines=True)

If res contains a newline at the end, remove it with res.strip(). Finally, cast res to float with float(res).

Upvotes: 3

Related Questions