3 回答
TA贡献1911条经验 获得超7个赞
对于那些回顾了先前的答案的人,从版本“ Python 2.6”开始,对于原始张贴者的问题有了新的答案。
在Python 2.6及更高版本中,您可以禁用print语句,而使用print函数,然后使用自己的print函数覆盖print函数:
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)
当然,您现在需要考虑此打印功能仅在模块范围内。您可以选择覆盖__builtin__.print,但是您需要保存原始文件__builtin__.print; 可能与__builtin__名称空间混为一谈。
添加回答
举报