Reputation: 33202
I need to call InitGoogleLogging() when my C++ library is imported in Python. My C++ library uses Boost.Python.
How do I call functions when the library is imported?
Upvotes: 2
Views: 2212
Reputation: 2137
There are no real "definitions" in python. Any code you put in a .py module is executed when you import it. It just happens to be that most of the time the code put in the package files is the "definiton" code like class or def. In practice, that code still gets executed, it just creates your class and function definitions as a result. Calling a function from the root namespace (indentation) in the module will cause it to get called as soon as the module is loaded.
Just put them into the __init__.py. See http://www.boost.org/doc/libs/1_45_0/libs/python/doc/tutorial/doc/html/python/techniques.html#python.extending_wrapped_objects_in_python where it talks about exporting your package with an alias and then flatning your namespace in init.py.
i.e. (this would be __init__.py in a a subdirectory named foo):
from _foo import *
InitGoogleLogging()
Another alternative is calling it directly from the C++ wrapper module:
BOOST_PYTHON_MODULE(foo)
{
InitGoogleLogging();
class_<Foo>("Foo")
.def("bar", &bar)
;
}
Upvotes: 6