(3.2) Overload print() using the C API?

Chris Angelico rosuav at gmail.com
Thu Apr 26 17:49:10 EDT 2012


On Fri, Apr 27, 2012 at 5:28 AM, Peter Faulks <faulksp at iinet.net.au> wrote:
> Cheers,
>
> Yes was aware this would (might) be possible in 3.x only.
>
> "All you have to do is assign to print". Sounds great! Can some kind soul
> hit me with a clue stick? Were do I look in the API?

(We prefer to avoid top-posting on this list.)

Many of the PyRun_* functions take object references for the globals
and locals. With those, you can import builtins or main and then use
dictionary functions to change it before calling PyRun_something.

If you're currently using a function that doesn't accept PyObject
*globals (eg PyRun_SimpleString), you'll have to do a bit more work -
effectively, you'll be doing for yourself what the extra-high-level
function is doing for you - before you can start tinkering like this.

PyObject *globals=PyModule_GetDict(PyImport_AddModule("__main__"));

(You could instead import __builtin__ for a slightly different environment.)

Hope that helps!

ChrisA



More information about the Python-list mailing list