小编Big*_*ndy的帖子

将时间戳添加到打印功能

我目前正在用 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__'

python python-3.x

1
推荐指数
1
解决办法
1201
查看次数

标签 统计

python ×1

python-3.x ×1