2

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.

2
  • Do you need help creating the class or adding it to the module? Commented Apr 25, 2012 at 2:42
  • @IgnacioVazquez-Abrams Adding it to the module Commented Apr 25, 2012 at 11:43

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

While this works when the desired module is imported, it does not work when one just has called Py_InitModule()

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.