【发布时间】:2017-01-08 13:50:56
【问题描述】:
我需要将与控制台中显示的日志相同的日志保存到文件中,因此我编辑了 sys.stdout。 (使用来自Redirect stdout to a file in Python?的代码)
但是当我尝试通过在写入功能之前添加一些内容来编辑文本时,问题就出现了。结果这个“[stack]”在文本变量之前和之后添加。
import sys
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.file = open("log.txt", "a")
def flush(self):
self.terminal.flush()
self.file.flush()
def write(self, text):
self.terminal.write("[stack]" + text)
self.file.write(text)
self.flush();
sys.stdout = Logger()
print "Test log"
print "Another test log"
结果:
[stack]Test log[stack]
[stack]Another test log[stack]
【问题讨论】:
-
print "Test log"被执行为write("Test log")和write("\n")- 所以你得到write("[stack]" + "Test log")和write("[stack]" + "\n")。尝试使用逗号print "Test", "log",你会得到更多[stack]-[stack]Test[stack] [stack]log[stack]:)