I am embedding python in my C++ application using boost python. I am a C++ programmer, with very limited knowledge of Python.
I have a C++ class, PyExpression
. Each instance of this class has a string expStr
, which is a short user-entered (at runtime) python program, that is executed by calling boost::python::exec
. Briefly, I have this set up as:
//import main and its globals
bp::object main = bp::import("__main__");
bp::object main_namespace = main.attr("__dict__");
where main
and main_namespace
are members of the C++ class PyExpression
.
void PyExpression::Run()
{
bp::object pyrun = exec(expStr,main_namespace);
}
The problem here is that different C++ instances of PyExpression
modify the same global python namespace, main_namespace
, and I want each PyExpression
instance to have its own "global" namespace.
If I pass in boost::python::dict class_dict
instead of main_namespace
above, it works at a basic level. But if PyExpression::expStr
imports a module, e.g. import sys
, then I get an ImportError
. Also, using class_dict
, I can no longer call globals()
, locals()
, vars()
, as they all become undefined.
I have also tried exposing PyExpression
as a python module. Briefly,
BOOST_PYTHON_MODULE(PyExpModule)
{
bp::class_<PyExpression>("PyExpression", bp::no_init)
//a couple .def functions
}
int pyImport = PyImport_AppendInittab( "PyExpModule", &initPyExpModule );
bp::object thisExpModule = bp::object( (bp::handle<>(PyImport_ImportModule("PyExpModule"))) );
bp::object PyExp_namespace = thisExpModule.attr("__dict__");
Unfortunately, using PyExp_namespace
, again I get the ImportError when the string to be executed imports a python module, and again, the namespace is shared between all instances of PyExpression
.
In short, I want to be able to use a namespace object/dictionary, that is preferably a class member of PyExpression
, have only that instance of PyExpression
have access to the namespace, and the namespace to act like a global namespace such that other modules can be imported, and the `globals(), locals(), vars() are all defined.
If anyone can point me to a sketch of working code, I would very much appreciate it. I can't find relevant material on this problem.