embedding python in c++: python script not recognized

烂漫一生 提交于 2020-01-06 07:14:20

问题


I am trying to embed python script into c++ project. Below is what I have tried so far.

#include<iostream>
#include <Python.h>

int
main()
{
    Py_Initialize();
    PyObject* sysPath = PySys_GetObject("path"); 
    PyObject* modPath = PyBytes_FromString("C:\\Users\\naal\\Documents\\Visual Studio 2017\\Projects\\Project1\pyscripts");
    int result = PyList_Insert(sysPath,0, modPath);
    PyObject *pModule = PyImport_ImportModule("myscript2");
    printf("%p\n", pModule);
    return 0;
}

below is the python script "myscript2.py"

def find_me():
    print("hey you found me")

The problem is, the main module is not able to find the python script i.e object pyModule is always NULL, no matter how I change python script path.

What am I doing wrong ?


回答1:


I ended up implementing this in another way.

#include<iostream>
#include <Python.h>

int main() {    
       std::string location = "C:\\Users\\myscript.py";     
       const char* file_location = location.c_str();    FILE* file_pointer;          
       Py_Initialize();
       file_pointer = _Py_fopen(file_location, "r");
       PyRun_SimpleFile(file_pointer, file_location);

       Py_Finalize();
       return 1;
       }

The above seemed to work. I still don't know why the SYSPATH idea originially mentioned in the question didn't work.



来源:https://stackoverflow.com/questions/55449475/embedding-python-in-c-python-script-not-recognized

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!