使用Python将stdout和stderr记录到日志文件';与';陈述
我想使用“with”语句将Python代码块的std输出记录到一个文件中:使用Python将stdout和stderr记录到日志文件';与';陈述,python,Python,我想使用“with”语句将Python代码块的std输出记录到一个文件中: with log_to_file('log'): # execute code 手动定义日志文件是最简单的方法,例如: import sys class log_to_file(): def __init__(self, filename): self.f = open(filename, 'wb') def __enter__(self): self.std
with log_to_file('log'):
# execute code
手动定义日志文件
是最简单的方法,例如:
import sys
class log_to_file():
def __init__(self, filename):
self.f = open(filename, 'wb')
def __enter__(self):
self.stdout = sys.stdout
self.stderr = sys.stderr
sys.stdout = self.f
sys.stderr = self.f
def __exit__(self, type, value, traceback):
sys.stdout = self.stdout
sys.stderr = self.stderr
或者已经有一个内置类可以做到这一点了吗?我唯一能建议的是使用
contextmanager
装饰器,但我不认为这真的更好
from contextlib import contextmanager
@contextmanager
def stdouterrlog(logfile):
with open(logfile, 'wb') as lf:
stdout = sys.stdout
stderr = sys.stderr
sys.stdout = lf
sys.stderr = lf
yield lf # support 'with stdouterrlog(x) as logfile'
sys.stdout = stdout
sys.stderr = stderr
看看这个问题。这似乎是你要找的。注意:其中一个答案使用现有的日志模块,而其他答案使用多处理。您的方法很好,即使您在
\uuuuuu exit\uuuuuuu
:)上没有关闭文件。我喜欢。您希望得到什么样的答案?我将给出一个评论:不,没有内置类可以做到这一点。在类似的行中,AssertPrints
上下文管理器用于测试:为什么不使用文件
对象固有的上下文管理器?也就是说,让stdouterlog
be的主体以open(logfile,'wb')作为logfile:\n(do sys.stdout stuff…)\n生成logfile
\n(undo sys.stdout stuff…)是的,这将节省一行额外的代码…除了您可能还应该将整个内容包装在try
/块中之外,否则,未经处理的错误将使日志文件保持打开状态。