将时间戳添加到打印功能

Big*_*ndy 1 python python-3.x

我目前正在用 python 3.7 编写自己的程序,并且想在打印的前面添加一个时间戳,格式如下:

<hh:mm:ss> WhateverImPrinting
Run Code Online (Sandbox Code Playgroud)

我查看了其他论坛,得到了一些使用 sys.stdout 的代码,使用 write 函数覆盖了文本。

我的问题是它在打印之前和之后都返回时间戳。

例如 <14:21:51> Hello<14:21:51>

这应该是:

<14:21:51> Hello
Run Code Online (Sandbox Code Playgroud)

我的代码:

old_f = sys.stdout  # Get old print output


class PrintTimestamp:
    # @staticmethod
    def write(self, x):
        old_f.write("<{}> {}".format(str(pC.Timestamp.hhmmss()), x))

    # @staticmethod
    def flush(self):
        pass


sys.stdout = PrintTimestamp()    # Set new print output
Run Code Online (Sandbox Code Playgroud)

我在所有的类和函数之后都运行了这个,但之前 if __name__ == '__main__'

Sel*_*cuk 8

您可以简单地覆盖printPython 3.x 中的函数:

from datetime import datetime

old_print = print

def timestamped_print(*args, **kwargs):
  old_print(datetime.now(), *args, **kwargs)

print = timestamped_print
Run Code Online (Sandbox Code Playgroud)

然后

print("Test")
Run Code Online (Sandbox Code Playgroud)

应该打印

2019-09-30 01:23:44.67890 Test
Run Code Online (Sandbox Code Playgroud)