[C++-sig] PyFinalize Safety

Stefan Seefeld seefeld at sympatico.ca
Sun Feb 18 16:18:16 CET 2007


Dave Wolfe wrote:

> I have a somewhat related question.  I have a function to create python
> objects that looks like this:
> 
> bpl::object CreatePythonCallable(const char* fileName,
>                                  const char* className)
> {
>     try {
>         bpl::object main = bpl::import("__main__");
>         bpl::object global = main.attr("__dict__");
>         bpl::exec_file(fileName, global, global);
>         bpl::object ClassType = global[className];
>         bpl::object retval = ClassType();
>         return retval;
>     }
>     catch (bpl::error_already_set const&) {
>         std::cerr << GetPythonException();
>     }
> 
>     return bpl::object();  // <-- return 'None'
> }
> 
> This works fine, except that test blocks in my code that look like this:
> 
>   if __name__ == '__main__':
>       DoTests()
> 
> get executed when run from C++.  How do I arrange for the code to be
> executed in another context, using only boost.python calls?

The bpl::exec_file(filename) call is similar to calling 'python filename' in
a shell. Thus, __name__ is indeed set to __main__. If you don't want that,
you should execute a different script that imports your module, thereby not
acting in stand-alone mode.
(Reading in the whole file into string and then using bpl::exec() instead of
bpl::exec_file() may work, too. I'm not sure.)

HTH,
		Stefan

-- 

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



More information about the Cplusplus-sig mailing list