你看不到任何东西的事实可能与缓冲正在发生的事实有关。所以你只能得到每4千分左右的文本输出。
相反,试试这样的方法:class OutputSplitter(object):
def __init__(self, real_output, *open_files):
self.__stdout = real_output
self.__fds = open_files
self.encoding = real_output.encoding
def write(self, string):
self.__stdout.write(string) # don't catch exception on that one.
self.__stdout.flush()
for fd in self.__fds:
try:
fd.write(string)
fd.flush()
except IOError:
pass # do what you want here.
def flush(self):
pass # already flushed
然后用该类装饰sys.stdout,并使用如下代码:stdout_saved = sys.stdout
logfile = open("log.txt","a") # check exception on that one.
sys.stdout = OutputSplitter(stdout_saved, logfile)
这样,每个输出(包括print)都会刷新到标准输出和指定文件。可能需要调整,因为我还没有测试这个实现。
当然,在打印消息时会看到(大多数情况下很小的)性能损失。