[C++-sig] Creating a python class from c++

Stefan Seefeld seefeld at sympatico.ca
Sat Nov 18 17:00:28 CET 2006


James Healey wrote:
> Ok got the exception catch working and printing out
> the error and stack trace.
> 
> ImportError: __import__ not found
> 
> Is the error that I am getting.

OK, I think I now understand what's going on:

The code I proposed looked like this:

namespace bpl = boost::python;
bpl::dict global;
bpl::exec_file("your_file.py", global, global);


Note that 'global' is completely empty, as thus is the environment seen by the script.
It appears we need to import the '__main__' module and take its dictionary instead, as
that provides some objects we are using:

bpl::object main = bpl::import("__main__");
bpl::dict global = main.attr("__dict__");
bpl::exec_file("your_file.py", global, global);

That should work.

Regards,
		Stefan

PS: And in case you are going to ask where the 'import' function
    is coming from: I added it at the same time as the exec / exec_file
    functions, so boost 1.33 doesn't have it yet. Here is a copy:

namespace boost
{
namespace python
{
object BOOST_PYTHON_DECL import(str name)
{
  // should be 'char const *' but older python versions don't use 'const' yet.
  char *n = extract<char *>(name);
  handle<> module(borrowed(PyImport_AddModule(n)));
  return object(module);
}
}
}



-- 

      ...ich hab' noch einen Koffer in Berlin...




More information about the Cplusplus-sig mailing list