使用活动标准输出(退格/更新)将Python标准输出记录到文件... [英] Logging Python stdout to File... with active stdout (backspacing/updating)

查看:184
本文介绍了使用活动标准输出(退格/更新)将Python标准输出记录到文件...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,所以使用此示例,我将标准输出记录到文件中并将其发送到终端.

Ok, so using this example, I'm logging my stdout to a file as well as sending it to the terminal.

但是当我查看日志文件时,不处理退格键,而是将其与输出一起打印.

But when I look at the log file, the backspaces are not processed, but printed along with the output.

以任何方式可以记录python脚本的stdout的最终"状态吗?

Any way I could log the "final" state of stdout of a python script?

推荐答案

以下是从您链接的答案中获取基本类并为\r\b添加一些正则表达式处理的解决方案:

Here is a solution that takes the basic class from the answer you linked and adds some regex handling for \r and \b:

import sys
import re

class Logger(object):
    def __init__(self, filename="Default.log"):
        self.terminal = sys.stdout
        self.log = open(filename, "a")
        self.cr_pattern = re.compile("^.*\r", re.M)
        self.bs_pattern = re.compile(".\b")

    def write(self, message):
        self.terminal.write(message)
        message = self.bs_pattern.sub('', self.cr_pattern.sub('', message))
        self.log.write(message)

sys.stdout = Logger("yourlogfilename.txt")
print "Hello\rGoodbyee\b world!"

示例运行:

$ python test.py
Goodbye world!
$ cat yourlogfilename.txt
Goodbye world!

请注意,通常您应将原始字符串文字用于正则表达式,这是不应该使用的罕见情况之一.

Note that normally you should use raw string literals for your regular expressions, this is one of the rare cases where you shouldn't.

这篇关于使用活动标准输出(退格/更新)将Python标准输出记录到文件...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆