I guess my problem is fairly straight-forward, however I can't find a way to solve it. My process is the following:
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?
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).
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With