Reputation: 11502
Im currently trying to embed the python interpreter into my application. Because my application uses the Poco API for logging, I want to make it accessable through the logging module in python too. The most easiest way for me to do this, is to provide a static set of function as an extension module to log a message and then to write a Handler subclass calling these functions.
Since I dont want the user to install any additional python modules and since I dont have the requirement to reuse my code outside of my embedded python interpreter, it would be great if one could just provide the static functions through Py_InitModule()
and then to add a hardcoded Handler subclass to the created module (hardcoded means: added at runtime but actually a const string which gets always interpreted at initialization).
My problem is that I dont know how to interpret a normal python class definition, e.g:
class Test:
someVar=1
so that it is added to a given module and then accesable as, e.g mymodule.Test
A solution can either be pure python based or work with the python c-api.
Upvotes: 2
Views: 1347
Reputation: 11502
I finally found the answere myself: There are actually 2 methods to execute code in the context of a module
Way 1
PyObject* module = Py_InitModule("poco",LoggingPocoMethods);
PyObject* code = Py_CompileString("class Test:\n\tdef __repr__(self):\n\t\treturn 'Hello world'","",Py_file_input);
PyImport_ExecCodeModule("poco",code);
This method has the drawback that the module will be reloaded which is not required at this stage.
Way 2
PyObject* module = Py_InitModule("poco",LoggingPocoMethods);
PyObject* mainModule = PyImport_AddModule("__main__");
PyObject* dict = PyModule_GetDict(module);
PyObject* mainDict = PyModule_GetDict(mainModule);
PyRun_String("def test():\n\tprint 'test'\n",Py_file_input,mainDict,dict);
Upvotes: 1
Reputation: 2804
To put something into a module, just assign it. Assuming class Test is defined as above, to attach it to module mymodule under that name, just write
mymodule.Test = Test
That’s it.
Upvotes: 0