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.
Any way I could log the "final" state of stdout of a python script?
解决方案
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!"
Example run:
$ 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.