Send value back from C ++ to python

I think my problem is pretty straight forward, however I cannot find a way to solve it. My process is as follows:

  • I am running Python script: Test.py.
  • Inside the script, I am calling a C ++ program.

Test.py:

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

      

I want the executable to ./Example

return a double that can be used later in my Python script. What's the best way to do this?

+3


source to share


2 answers


Here's a small example based on @ForceBru:

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))

      

+2


source


First of all, be sure to Example

output the correct data to stdout

. If it isn't, there is nothing you can do about it.

Then use the Python module subprocess

.



import subprocess

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

      

If it res

contains a newline at the end, remove it with res.strip()

. Finally, draw res

up float

with float(res)

.

+3


source







All Articles