我正在尝试使用此链接上的代码段运行脚本时将控制台日志复制到文件中。我尝试通过使用时间模块中的 strftime 添加时间戳来自定义它,但该代码片段现在在新行的开头和结尾都添加了时间戳:
2014-12-10 12:15:35: Working on local page 12014-12-10 12:15:35:
我做错了什么?我将如何解决此问题,以便时间戳仅显示在换行符的开头?
from time import strftime
class copyConsoleToFile(object):
""" Enables logging of console output to a file, use
>> tlogger = copyConsoleToFile('logfile.txt', 'w')
at the start of the code to start logging.
"""
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
sys.stdout = self
def close(self):
if self.stdout is not None:
sys.stdout = self.stdout
self.stdout = None
if self.file is not None:
self.file.close()
self.file = None
def write(self, data):
self.file.write(strftime("%Y-%m-%d %H:%M:%S") + ': ' + data)
self.stdout.write(data)
def flush(self):
self.file.flush()
self.stdout.flush()
def __del__(self):
self.close()
如注释中所述,似乎子进程为每行添加了额外的写入。我建议删除无用的额外字符:
with open('logfile.txt','r+') as fopen:
string = ""
for line in fopen.readlines():
string = string + line[:-23] + "n"
with open('logfile.txt','w') as fopen:
fopen.write(string)
该代码改编自: https://stackoverflow.com/a/45594783/1751393