我在网上找到了一些通常可用的代码,但我想在同一个程序中多次使用它(将不同的内容写入不同的文件,同时仍然在屏幕上打印整个过程)。
也就是说,当它关闭时,我认为sys.stdout关闭了,因此完全打印和再次使用此类失败。我尝试重新导入sys和其他愚蠢的东西,但我无法使其正常工作。
这是网站和代码 groups.google.com/group/comp.lang.python/browse_thread/thread/d25a9f5608e473af/
import sys
class MyWriter:
def __init__(self, stdout, filename):
self.stdout = stdout
self.logfile = file(filename, 'a')
def write(self, text):
self.stdout.write(text)
self.logfile.write(text)
def close(self):
# self.stdout.close()
self.logfile.close()
writer = MyWriter(sys.stdout, 'log.txt')
sys.stdout = writer
print 'test'