Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send value back from c++ to python

Tags:

c++

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?

like image 678
JbGT Avatar asked Apr 21 '26 00:04

JbGT


2 Answers

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

like image 65
ForceBru Avatar answered Apr 22 '26 12:04

ForceBru


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))
like image 25
dlavila Avatar answered Apr 22 '26 13:04

dlavila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!