[C++-sig] Executing scripts in other namespace than __main__
faboster at gmail.com
Thu Mar 18 05:42:35 CET 2010
Hi everybody, it's my annoying again.
I have a pure virtual class in C++ wich I have wrapped and exposed
(call it BaseClass), and I let the users inherit from it to make their
own class in their script. It's worth noting that I do not know the
name of such class they are creating. When I load only one script,
there's no problem in doing this:
object module_main = import("__main__");
object namespace_module_main = module_main.attr("__dict__");
exec("import sys\n", namespace_module_main,
object ignored = exec_file(boost::python::str("path/file1.py"),
//and as i don't know how the class they defined was named...
object ignored_ =
exec("l = dir()\n" //get everything defined in current dictionary
"class_ = None\n"
"for i in l:\n"
" res = eval(i)\n"
" if type(res) == type(BaseClass): class_ = res\n"
//if we've got a class derived from BaseClass, we save it to "class_"
"if class_ is None: raise Error()\n"
, this->namespace_modulo_local, this->namespace_modulo_local);
object class_ = namespace_module_main["class_"]; //get the class object
object instance_ = class_();
BaseClass *bc = extract<BaseClass*>(instance_);
This works quite well when I only load one module. But if I load 2 or
more modules, the method I use to extract a class derived from
BaseClass is useless, since there are two or more classes derived from
BaseClass in __main__ and I don't know which one I will get.
So I thought I could run each script in it's own namespace, and then
using the same method for retrieving the class, but in every
individual namespace, ensuring I will get the derived class from the
specified script. How can I acommplish this?
More information about the Cplusplus-sig