Globally override built-in print function?

Dave W. evadeflow at gmail.com
Thu Apr 15 19:08:42 EDT 2010


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

py = InteractiveInterpreter()

if not hasattr(sys, "ps1"): sys.ps1 = ">>> "
if not hasattr(sys, "ps2"): sys.ps2 = "... "

banner = ("Python %s\n%s\n" % (sys.version, sys.platform) +
          'Type "help", "copyright", "credits" or "license" '
          'for more info.\n')

sys.stdout.write(banner)
sys.stdout.write(sys.ps1)
while True:
    try:
        with global_printhook(printhook):
            result = py.runsource(raw_input())
            if result is None:
                sys.stdout.write(sys.ps2)
            elif result is True:
                py.runcode(result)
    except EOFError:
        break
    else:
        sys.stdout.write(sys.ps1)



More information about the Python-list mailing list