Globally override built-in print function?

Dave W. evadeflow at
Fri Apr 16 04:17:51 CEST 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.  <snip>

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

I'm pretty sure this is semantically equivalent to my original code,
but I gave it a try anyway.  FWIW, it doesn't work, either. :-}

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

I'm starting to believe it, but... I thought that one of the
benefits of making print a function was that it *could* be globally
replaced. So far I've had no luck injecting a custom print
replacement into other modules.  Is this really not possible?

More information about the Python-list mailing list