Python initialization segfault

I am building an application with boost.python. I have one singleton class with a name ScriptsManager, it has a function initPythonthat does:

mMainModule = bp::import("__main__");
mMainNamespace = bp::import("__dict__");

bp::object ignored = bp::exec("hello = file('hello.txt', 'w')\n"
                  "hello.write('Hello world!')\n"
                  "hello.close()", mMainNamespace);

both mMainModule, mMainNamespaceare equal boost::python::object.

So, when I launch the application, I get:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()
(gdb) bt
#0  0x0000000000000000 in ?? ()
#1  0x00007ffff5d5efd9 in PyEval_GetGlobals () from /usr/lib/libpython2.7.so.1.0
#2  0x00007ffff5d79113 in PyImport_Import () from /usr/lib/libpython2.7.so.1.0
#3  0x00007ffff5d7935c in PyImport_ImportModule () from /usr/lib/libpython2.7.so.1.0
#4  0x00007ffff5a6d8bd in boost::python::import(boost::python::str) () from /usr/lib/libboost_python.so.1.46.0
#5  0x0000000000510b1b in ScriptsManager::initPython (this=0x7b6850) at /home/ockonal/Workspace/Themisto/src/Core/ScriptsManager.cpp:24
#6  0x0000000000547650 in Application::main (args=...) at /home/ockonal/Workspace/Themisto/src/main.cpp:60
#7  0x00007ffff4ebbf86 in main () from /usr/lib/libclan22App-2.2.so.1
#8  0x00007ffff24c4dcd in __libc_start_main () from /lib/libc.so.6
#9  0x00000000004c9769 in _start ()

What could be wrong here?


UPD1

When I call Py_Initialize()before bp::import, I get:

call termination after throwing instance "Push :: python :: error_already_set


UPD2

It seems that the problem was in the code:

mMainNamespace = bp::import("__dict__");

Result Code:

Py_Initialize();
mMainModule = bp::import("__main__");
mMainNamespace = mMainModule.attr("__dict__");

I am not sure if this is correct.


UPD3

Yep, 2 - updated. So strange, mMainNamespace = bp::import("__dict__")it is written in official enhancement docs.

+5
1

, :

int main (int argc, char** argv)
{
    try
    {
        // If you're going to use threads: PyEval_InitThreads();
        Py_Initialize();
        PySys_SetArgv(argc, argv);

        bp::object mMainModule = bp::import('__main__');
        bp::object mMainNamespace = mMainModule.attr('__dict__');

        bp::object ignored = bp::exec("hello = file('hello.txt', 'w')\n"
              "hello.write('Hello world!')\n"
              "hello.close()", mMainNamespace);
   }
   catch (bp::error_already_set const&)
   {
        PyErr_Print();
   }
}

Py_Initialize() , try { ... } catch () { ... } -block Python, , , bp::import , : -)

+3

All Articles