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__名稱空間混為一談。
添加回答
舉報