【问题标题】:How to embed a python code which sets flags in C++如何嵌入在 C++ 中设置标志的 python 代码
【发布时间】:2019-04-08 04:33:02
【问题描述】:

我找不到嵌入 python 代码的方法,该代码在 https://docs.python.org/3.5/extending/embedding.html 的 C++ 代码中设置标志。

我有这个python代码test.py

import tensorflow as tf

# Settings
flags = tf.app.flags
FLAGS = flags.FLAGS

#core params..
flags.DEFINE_string('model', 'gcn', 'model name')
flags.DEFINE_float('learning_rate', 0.01, 'initial learning rate')
flags.DEFINE_string("model_size", "small", "define model size")


def main(argv=None):
    print("Flags Set")
    print(FLAGS.learning_rate)

if __name__ == '__main__':
    tf.app.run()

当我执行命令时:

python -m test --learning_rate 0.0002

输出是:

Flags Set
0.0002

如何在 C++ 中嵌入上述 python 代码并调用它?

【问题讨论】:

  • 您的第一句话有点奇怪,因为您链接了确切的文档。页面解释了如何做到这一点。 C++ 代码通常被编译为二进制(尽管它可能会像我最近学到的一样被解释)。 Python 代码通常由 Python 解释器解释(尽管可能有编译器,例如 IronPython)。因此,这就是文档。描述:在 C 或 C++ 程序中嵌入 Python 解释器。 C++ 代码还可以通过其他类型、变量和函数来扩展 Python 以实现互操作。 Python 和 C++。
  • 根据文档的描述,嵌入的python代码函数需要通过./executable 来调用。但是当我单独执行我的python代码时,我想给出标志值(例如:--learning_rate 0.0002)。当我在 C++ 中嵌入 python 代码时,我找不到设置这些标志的方法
  • 首先,看看这个:SO: How to access a Python global variable from C?。 (我用google "find a specific python variable c c++" google 来找到这个。)我必须承认,我需要一段时间才能正确地结合 C++ 和 Python(并且需要更长的时间才能使其稳定),但我只使用了 Python 文档。或谷歌研究掌握它。有一点耐心,这是可能的。 ;-)
  • 可能是,我误解了你的问题。如果你问如何通过PyRun_ 函数传递命令行参数 -> 我发现这个:SO: Pass argument to PyRun_File(***) 链接到这篇博客文章:Passing Parameters in From C to Pyhton.
  • docs.python.org/3.5/extending/embedding.html 是关于在 python 脚本中执行一个函数而不是 python 脚本本身。

标签: python c++ flags embedding


【解决方案1】:

你有两个选择,

1.只需使用system()执行python脚本,

system("python -m /path/to/test.py  --learning_rate 0.0002");

2.如下使用Python/C Api,

#include <python3.6/Python.h>
#include<iostream>
using namespace std;

int main(int argc, char *argv[])
{
    FILE* file;
    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    wchar_t** _argv;
    for(int i=0; i<argc; i++){
        wchar_t *arg = Py_DecodeLocale(argv[i], NULL);
        _argv[i] = arg;
    }
    Py_SetProgramName(program);
    Py_Initialize();   
    PySys_SetArgv(argc, _argv);
    file = fopen("/path/to/test.py","r");
    PyRun_SimpleFile(file, "/path/to/test.py");
    Py_Finalize();
    return 0;
}

如果你在 a.out 中得到一个可执行文件,你可以像下面这样运行它,

./a.out --learning_rate 0.0002

注意:-我在 python3.6m 文件夹中有 Python.h,我使用标志 -lpython3.6m 进行编译。

【讨论】:

  • 非常感谢。我更喜欢第二种选择。但是,我对上面的代码做了一些小改动。我把 Py_Initialize();作为 main 方法的第一行。否则,我得到 ImportError: No module named 'tensorflow'
  • 如果我有 tensorflow 我会测试它,很高兴它对你有用。
  • 如果我将此主方法内容放入一个单独的函数并从两个线程调用该函数,我最终会出现分段错误。你有答案吗?
猜你喜欢
  • 2017-11-03
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
  • 2021-06-14
  • 1970-01-01
  • 2011-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多