简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM