[C++-sig] Importing and internal modules

Peter LaDow petela at gocougs.wsu.edu
Mon Sep 29 21:20:06 CEST 2008


I'm not sure if my subject is clear (probably not), but I'll try to
describe what I am trying to do here.

A commercial tool we are using is capable of loading a shared library
as an extension, and we'd like to use Python to script much of the
extension.  To that end, I am embedding Python in our own shared
library.  The scripted part of the extension is a collection of
callback functions from the shared library into Python.  I also want
to expose an API to the extension.

So, I have created an extension using Boost and the BOOST_PYTHON_MODULE, i.e.:

namespace bp = boost::python;

BOOST_PYTHON_MODULE(foo)
{
  bp::def("foo1", foo1);
  bp::def("foo2", foo2);
}

And then I make sure to append foo to the inittab before calling
Py_Initialize():

PyImport_AppendInittab("foo", initfoo);
Py_Initialize();

No problems so far.  In fact, I can use foo in the Python script as
long as I import it, i.e. ("from foo import *").  However, here's were
I am running into trouble.

The scriptable part is a module.  It exposes a set of functions, so
I'd really like to just import that module, and not execute it.  So, I
do the following:

bp::object main = bp::import("__main__");
bp::object globals(main.attr("__dict__"));

// Import "foo"
bp::exec("from foo import *", globals, globals);

// Import the scriptable code
bp::exec("from script import *", globals, globals);

And here's an example of a script I am trying to import:

def bar1():
  foo1()
  print "Called bar1!"

def bar2():
  foo2()
  print "Called bar2!"

Now, the import for this fails with:

NameError:  global name 'foo1" is not defined

Unless I put "from foo import *" at the top of the script.  I want the
'foo' module already imported into the script.  That's the point of
the first of the imports.

I'm sure I'm missing something obvious here.  Any help would be
greatly appreciated.

Thanks,
Pete
-- 
--
"To love for the sake of being loved is human;  to love for the sake
of loving is Angelic."  -- Alphonse de Lamartine



More information about the Cplusplus-sig mailing list