For those reviewing the previously dated answers, as of version release "Python 2.6" there is a new answer to the original poster's question.
In Python 2.6 and up, you can disable the print statement in favor of the print function, and then override the print function with your own print function:
from __future__ import print_function
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string,
# Python comments, other future statements, or blank lines before the __future__ line.
try:
import __builtin__
except ImportError:
# Python 3
import builtins as __builtin__
def print(*args, **kwargs):
"""My custom print() function."""
# Adding new arguments to the print function signature
# is probably a bad idea.
# Instead consider testing if custom argument keywords
# are present in kwargs
__builtin__.print('My overridden print() function!')
return __builtin__.print(*args, **kwargs)
Of course you'll need to consider that this print function is only module wide at this point. You could choose to override __builtin__.print
, but you'll need to save the original __builtin__.print
; likely mucking with the __builtin__
namespace.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…