将Python控制台输出复制到文件并添加时间戳

时间:2014-12-10 11:23:22

标签: python

我正在尝试使用this link上的代码段运行脚本时将控制台日志复制到文件中。我尝试通过使用时间模块中的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()

1 个答案:

答案 0 :(得分:0)

如评论中所述,似乎子进程向每行添加了额外的写入。我建议删除无用的多余字符:

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