Embedded Python 2.7.2 Import a module from a user directory

I am embedding Python in a C / C ++ application that will have a specific API.

An application needs to instantiate classes defined in a script that are structured like this:

class userscript1: def __init__(self): ##do something here... def method1(self): ## method that can be called by the C/C++ app...etc 

I managed in the past (to prove the concept) to do this using the following code type:

 PyObject* pName = PyString_FromString("userscript.py"); PyObject* pModule = PyImport_Import(pName); PyObject* pDict = PyModule_GetDict(pModule); PyObject* pClass = PyDict_GetItemString(pDict, "userscript"); PyObject* scriptHandle = PyObject_CallObject(pClass, NULL); 

Now that I am in a more production environment, this does not work on the PyImport_Import line - I think it could be because I'm trying to add a directory to the script name, for example.

 PyObject* pName = PyString_FromString("E:\\scriptlocation\\userscript.py"); 

Now, to give you an idea of โ€‹โ€‹what I tried, I tried changing the system path before all these calls to make it look for this module. Basically tried to programmatically modify sys.path:

 PyObject* sysPath = PySys_GetObject("path"); PyObject* path = PyString_FromString(scriptDirectoryName); int result = PyList_Insert(sysPath, 0, path); 

These lines work fine, but do not affect my code. Obviously, my real code has an error checking boat which I excluded, so don't worry about that!

So my question is: how do I insert the built-in interpreter correctly in my scripts so that I can instantiate classes?

+8
c ++ c python python-c-api python-embedding
source share
1 answer

you need to specify userscript , not userscript.py also use PyImport_ImportModule , it takes char * directly

userscript.py means py module in userscript package

this code works for me:

 #include <stdio.h> #include <stdlib.h> #include <Python.h> int main(void) { const char *scriptDirectoryName = "/tmp"; Py_Initialize(); PyObject *sysPath = PySys_GetObject("path"); PyObject *path = PyString_FromString(scriptDirectoryName); int result = PyList_Insert(sysPath, 0, path); PyObject *pModule = PyImport_ImportModule("userscript"); if (PyErr_Occurred()) PyErr_Print(); printf("%p\n", pModule); Py_Finalize(); return 0; } 
+16
source share

All Articles