簡體   English   中英

如何嵌入在 C++ 中設置標志的 python 代碼

[英]How to embed a python code which sets flags in C++

我找不到在https://docs.python.org/3.5/extending/embedding.html 中嵌入在 C++ 代碼中設置標志的 python 代碼的方法。

我有這個 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

如何將上述 python 代碼嵌入到 C++ 中並調用它?

你有兩個選擇,

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 進行編譯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM