如何嵌入一个在C ++中设置标志的python代码

问题描述 投票:1回答:1

我找不到一种方法来嵌入一个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代码并调用它?

python c++ flags embedding
1个回答
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进行编译。

© www.soinside.com 2019 - 2024. All rights reserved.