import sys from datetime import datetime def print_with_timestamp(*args, sep=' ', end='\n', file=None, flush=False, time_format="%Y-%m-%d %H:%M:%S"): """ 与 print 类似,但在输出内容前加时间戳前缀。 - *args: 要打印的对象(会用 sep 连接) - sep, end, file, flush: 与内置 print 相同 - time_format: 时间格式,默认 '%Y-%m-%d %H:%M:%S',遵循 datetime.strftime 格式 """ if file is None: file = sys.stdout ts = datetime.now().strftime(time_format) body = sep.join(str(a) for a in args) output = f'{ts} --> {body}' print(output, end=end, file=file, flush=flush) if __name__ == "__main__": print_with_timestamp(f"Test output")