简体   繁体   English

将值从c ++发送回python

[英]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. 我运行一个Python脚本:Test.py.
  2. Within that script, I am calling a c++ program. 在那个脚本中,我正在调用一个c ++程序。

Test.py: 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. 我想要./Example可执行文件返回一个可以在我的Python脚本中使用的double。 What is the best way to do that? 最好的方法是什么?

First of all, make sure Example outputs the desired data to stdout . 首先, 确保Example将所需数据输出到stdout If it's not, you can do nothing about it. 如果不是,你就无能为力了。

Then use the Python's subprocess module. 然后使用Python的subprocess模块。

import subprocess

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

If res contains a newline at the end, remove it with res.strip() . 如果res在末尾包含换行符,请使用res.strip()将其删除。 Finally, cast res to float with float(res) . 最后,使用float(res)resfloat

Here's a small example based on @ForceBru answer: 这是一个基于@ForceBru答案的小例子:

example.cpp , compile with g++ example.cpp -o example example.cpp ,用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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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