我不是 100% 清楚 Velizar 的现有答案如何处理输出与多个 \n 一起发送的情况。我不确定它是否可靠地工作,如果确实如此,我认为它可能依赖于输出流的潜在无证行为。
这是我的解决方案,它在每个打印行的开头添加时间戳,并在没有 \n 的情况下可靠地处理多行/行:
import time
import sys
class TimestampFilter:
# pending_output stores any output passed to write where a \n has not yet been found
pending_output = ''
def write(self, message):
output = self.pending_output + message
(output, not_used, self.pending_output) = output.rpartition('\n')
if output != '':
timestamp = time.strftime("%Y-%m-%d %X")
output = timestamp + " " + output.replace("\n", "\n"+timestamp+" ")
print(output, file=sys.__stdout__)
sys.__stdout__.flush()
sys.stdout = TimestampFilter()