1
我想创建一个函数,该命令会保存每个print
命令的记录,并将每个命令的字符串存储到文件的新行中。将所有打印在文件中的日志
def log(line):
with open('file.txt', "a") as f:
f.write('\n' + line)
这是我有什么,但有没有办法做我使用Python说的吗?
我想创建一个函数,该命令会保存每个print
命令的记录,并将每个命令的字符串存储到文件的新行中。将所有打印在文件中的日志
def log(line):
with open('file.txt', "a") as f:
f.write('\n' + line)
这是我有什么,但有没有办法做我使用Python说的吗?
尝试使用自定义类替换stdout
:
import sys
class LoggedStdout():
def __init__(self, filename = None):
self.filename = filename
def write(self, text):
sys.__stdout__.write(text)
if not self.filename is None:
self.log(text)
def log(self, line):
with open(self.filename, "a") as f:
f.write('\n' + line)
sys.stdout = LoggedStdout('file.txt')
print 'Hello world!'
这将不仅影响print
,而且还打印东西stdout
其它任何功能,但它往往是更好的。
对于生产模式日志记录,使用类似logging
module的东西要好得多,而不是在标准IO流中使用自制钩子。
哇,真酷!不知何故,我从未意识到你可以做到这一点。虽然你是对的,但使用标准模块更好。 – weronika