On 02/07/2010 04:51 PM, Murray Cumming wrote:
On Sun, 2010-02-07 at 09:51 -0500, Stefan Seefeld wrote:
Sorry, I don't understand the question. Can you give an example of
what
you want to do ? May be you want to "exec" some python code that
defines
a function, which you then want to extract and call later ?
That may look like this:

    // Retrieve the main module
    bpl::object main = bpl::import("__main__");
    // Retrieve the main module's namespace
    bpl::object global(main.attr("__dict__"));
    // Define the 'embedded' Python code...
    std::string py_code = "def greeting(): print 'hello world !'";
    // ...and execute it.
    bpl::object result = bpl::exec(py_code, global, global);
    // Extract the function
    bpl::object greeting = global["greeting"];
Yes, this last line is what I figured out from some other example code.
It does work for me. Thanks.

I guess it make sense in terms of the weird Python C API, but it's all
far from obvious without knowledge of that.

I think this has nothing to do with the C API, but rather the way the "exec" builtin function is defined (i.e., within Python itself): It executes some Python code within the context of a 'global' and a 'local' namespace which may be provided to the "exec" call. It also returns an object, but that is in general rather useless (only useful for error-checkin inside the C API). The real effects of the invocation are to be found in the 'global' and 'local' namespaces, whose content may have changed...

Thanks again.

You are welcome.

        Stefan


--

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

_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
http://mail.python.org/mailman/listinfo/cplusplus-sig

Reply via email to