已经有一个几千行的python文件,里面有很多的print语句,我现在需要在print语言中添加print打印的时间文本,如何快速实现

你可以在代码中添加一个装饰器函数,用于在每个 print 语句前面添加时间戳。这样可以让你在不修改每个 print 语句的情况下快速实现你的需求。

以下是一个示例装饰器函数,它将在每个 print 语句前添加一个时间戳:

import datetime

def add_timestamp_to_prints(func):
    def wrapper(*args, **kwargs):
        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'), end=' ')
        return func(*args, **kwargs)
    return wrapper

使用这个装饰器函数的方法很简单:只需在 print 语句前面添加 @add_timestamp_to_prints 即可。下面是一个示例代码,演示如何使用这个装饰器函数:

@add_timestamp_to_prints
def my_func():
    print("This is a test")

my_func()

这段代码会输出类似于以下内容的内容:

2022-03-15 09:12:23.123456 This is a test

你可能感兴趣的:(python,开发语言,numpy)