This changes the behavior of the print
statement without forcing you to change
print "foo"
to
print("foo")
import sys
_stdout = sys.stdout
class MyStream(object):
def __init__(self, target):
self.target = target
def write(self, s):
s = 'Foo : {!r}'.format(s)
self.target.write(s)
sys.stdout = MyStream(sys.stdout)
print 'Hi'
sys.stdout = _stdout # return print to its old behavior
yields
Foo : 'Hi'
This could be neatened with a context manager, but if you don't want to change your print
statements into print
functions, you probably don't want to have to wrap your print
statements in a context manager either.
So, a better, a more civilized way would be to use
2to3 --write --fix print test.py
to automatically change all the print
statements in your code (e.g. test.py above) into print
functions. Then you can change the behaviour by redefining the print
function:
from __future__ import print_function
import __builtin__
def print(*args, **kwargs):
__builtin__.print('Foo:', *args, **kwargs)
print('Hi')
yields
Foo: Hi