Categories

See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More

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

General Tech Bugs & Fixes
Max. 2000 characters
Replies

usr_profile.png
Dipti Singh

User

( 7 months ago )

 

I couldn't find a way to embed a python code which sets flags in C++ code at https://docs.python.org/3.5/extending/embedding.html.

I have this python code 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()

when I execute the command:

python -m test --learning_rate 0.0002

The output is:

Flags Set
0.0002

How can I embed the above python code in C++ and invoke it?

usr_profile.png
Charles Kyobe

User

( 7 months ago )

 

You have two options,

1. Simply execute the python script with system(),

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

2. Use Python/C Api as follows,

#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;
}

what's your interest


forum_ban8_5d8c5fd7cf6f7.gif