我想使用'with'语句将一大块Python代码的std输出记录到文件中:
with log_to_file('log'):
# execute code
最简单的方法是手动定义log_to_file
,例如:
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
或者是否有可以执行此操作的内置类?
答案 0 :(得分:2)
我唯一可以建议的是使用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