Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 向打印函数添加时间戳_Python_Python 3.x - Fatal编程技术网

Python 向打印函数添加时间戳

Python 向打印函数添加时间戳,python,python-3.x,Python,Python 3.x,我目前正在用python 3.7编写一个程序,并希望在打印前添加一个时间戳,格式如下: <hh:mm:ss> WhateverImPrinting WhateverImPrinting 我查看了其他论坛,得到一些使用sys.stdout的代码,使用write函数覆盖文本 我的问题是它在打印之前和之后都返回时间戳 e、 g.你好 这应该是: <14:21:51> Hello 你好 我的代码: old_f = sys.stdout # Get old print o

我目前正在用python 3.7编写一个程序,并希望在打印前添加一个时间戳,格式如下:

<hh:mm:ss> WhateverImPrinting
WhateverImPrinting
我查看了其他论坛,得到一些使用sys.stdout的代码,使用write函数覆盖文本

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

e、 g.
你好

这应该是:

<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
old_f=sys.stdout#获取旧打印输出
类打印时间戳:
#静态法
def写入(自我,x):
旧的写入(“{}”格式(str(pC.Timestamp.hhmmss()),x))
#静态法
def冲洗(自):
通过
sys.stdout=PrintTimestamp()#设置新的打印输出

我在我所有的类和函数之后运行了这个函数,但在
之前,如果uuu name uuu=='\uuuu main uuu'
您可以简单地覆盖Python 3.x中的
print
函数:

from datetime import datetime

old_print = print

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

print = timestamped_print
然后

应该打印

2019-09-30 01:23:44.67890 Test

您可以简单地重写Python 3.x中的
print
函数:

from datetime import datetime

old_print = print

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

print = timestamped_print
然后

应该打印

2019-09-30 01:23:44.67890 Test
给你

from datetime import datetime

class PrintTimeStamp():
   def write(self,x):
       ts = str(datetime.now.hour())+":"+str(datetime.now().minute)+":"+str(datetime.now().second)
       print("<{}> {}".format(str(ts),x)

pts = PrintTimeStamp()
pts.write("test")
从日期时间导入日期时间
类PrintTimeStamp():
def写入(自我,x):
ts=str(datetime.now.hour())+“:”+str(datetime.now().minute)+“:”+str(datetime.now().second)
打印(“{}”。格式(str(ts),x)
pts=打印时间戳()
pts.写入(“测试”)
给你

from datetime import datetime

class PrintTimeStamp():
   def write(self,x):
       ts = str(datetime.now.hour())+":"+str(datetime.now().minute)+":"+str(datetime.now().second)
       print("<{}> {}".format(str(ts),x)

pts = PrintTimeStamp()
pts.write("test")
从日期时间导入日期时间
类PrintTimeStamp():
def写入(自我,x):
ts=str(datetime.now.hour())+“:”+str(datetime.now().minute)+“:”+str(datetime.now().second)
打印(“{}”。格式(str(ts),x)
pts=打印时间戳()
pts.写入(“测试”)