Globally override built-in print function?

Robert Kern robert.kern at gmail.com
Fri Apr 16 01:18:01 CEST 2010


On 2010-04-15 18:08 PM, 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:
>
> c:\d>test.py
> Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
> (Intel)] win32
> Type "help", "copyright", "credits" or "license" for more info.
>>>> print("Hello?")
> Hello?
>>>>
>
> My custom print function isn't being called (see code below),
> I guess because its only being overridden in the current module?
> Is there some way to make InteractiveInterpreter/exec use my print
> function, or is this simply not possible?
>
> ----------
>
> ### File test.py ###
> from __future__ import print_function
> import sys
> from code import InteractiveInterpreter
> from contextlib import contextmanager
>
> def printhook(*args):
>      sys.stdout.write("printhook(): {0}\n".format(repr(args[0])))
>
> @contextmanager
> def global_printhook(printhook):
>      global print
>      print = printhook
>      yield
>      print = __builtins__.print

   old_print = __builtins__.print
   __builtins__.print = printhook
   yield
   __builtins__.print = old_print

But you really should replace sys.stdout and sys.stderr instead.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list