python - 为打印功能添加时间戳
问题描述
我目前正在用 python 3.7 编写自己的程序,并希望在打印的前面添加一个时间戳,格式如下:
<hh:mm:ss> WhateverImPrinting
我查看了其他论坛,得到了一些使用 sys.stdout 的代码,使用 write 函数覆盖了文本。
我的问题是它在打印之前和之后都返回时间戳。
例如<14:21:51> Hello<14:21:51>
这应该是:
<14:21:51> Hello
我的代码:
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
我在所有的课程和功能之后都运行了它,但在此之前if __name__ == '__main__'
解决方案
您可以简单地覆盖print
Python 3.x 中的函数:
from datetime import datetime
old_print = print
def timestamped_print(*args, **kwargs):
old_print(datetime.now(), *args, **kwargs)
print = timestamped_print
然后
print("Test")
应该打印
2019-09-30 01:23:44.67890 Test
推荐阅读
- flutter - 参数类型“Colors.red”不能分配给参数类型“Paint”
- python - 如何在seaborn relplot中更改标题中的标记大小
- icmp - 为什么 recvfrom() 函数可以接收所有流量
- zeromq - 为什么我不能为 zmq 编译基本的发送和接收模拟
- perl - 如何将变量添加到我的 Perl 单行中?
- python - 我无法在虚拟环境中安装求解器
- javascript - 如何添加对播放列表的支持?
- flutter-web - Flutter Web如何在本地读写图片文件?
- java - Java 检查计算器程序
- reactjs - 使用 React Link 并传递状态时页面不会刷新