+-

我试图找到一种方法在 python中将脚本执行日志重定向到文件以及stdout以pythonic方式.有没有简单的方法来实现这一目标?
最佳答案
我想出了这个[未经测试]
import sys
class Tee(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f.flush() # If you want the output to be visible immediately
def flush(self) :
for f in self.files:
f.flush()
f = open('out.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print "test" # This will go to stdout and the file out.txt
#use the original
sys.stdout = original
print "This won't appear on file" # Only on stdout
f.close()
打印>> python中的xyz将在xyz中使用write()函数.您可以使用自己的自定义对象.或者,你也可以让sys.stdout引用你的对象,在这种情况下,即使没有>> xyz它也会被编辑.
点击查看更多相关文章
转载注明原文:python – 如何输出到控制台和文件? - 乐贴网