Globally override built-in print function?

Peter Otten __peter__ at web.de
Fri Apr 16 09:49:09 CEST 2010


Dave W. wrote:

> I naively thought I could capture output from exec()'ed print
> invocations by (somehow) overriding 'print' globally.  But this
> seems not to be possible.  Or at least not easy:

Assigning a new function to the global print name affects only print() calls 
within your script, not the REPL. You have to redirect the latter and make 
sure that it is actually used instead of the print statement.

The easiest way I see to achieve that would be:

py.runsource("from __future__ import print_function")
py.runsource("from __main__ import printhook as print")

Peter




More information about the Python-list mailing list