How do you run a python script from a C++ program?

后端 未结 2 1287
庸人自扰
庸人自扰 2021-01-01 03:39

I have been able to find out a few things I know that you need to include Python.h and that you need to have

Py_Initialize();
//code that runs the python sc         


        
相关标签:
2条回答
  • 2021-01-01 04:27

    I found some good sources(https://docs.python.org/2/c-api/intro.html?highlight=py_initialize, https://docs.python.org/2/c-api/init.html?highlight=py_initialize), have you already seen it?

    0 讨论(0)
  • 2021-01-01 04:31

    The easiest way to run a Python script from within a C++ program is via PyRun_SimpleString(), as shown in the example at this web page:

    #include <Python.h>
    
    int main(int argc, char *argv[])
    {
      Py_SetProgramName(argv[0]);  /* optional but recommended */
      Py_Initialize();
      PyRun_SimpleString("from time import time,ctime\n"
                         "print 'Today is',ctime(time())\n");
      Py_Finalize();
      return 0;
    }
    

    If you want to run a script that's stored in a .py file instead of supplying the Python source text directly as a string, you can call PyRun_SimpleFile() instead of PyRun_SimpleString().

    0 讨论(0)
提交回复
热议问题