0

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 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.