事实上,你什么都看不到,可能与缓冲发生的事实有关。所以你只能得到每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
)被刷新到标准输出和指定的文件。可能需要调整,因为我没有测试过这个实现。
当然,打印消息时会期望看到(大部分时间很小)的性能损失。
不要忘记了''stderr''流重定向到''stdout''如果你也想捕捉: ''python -u MyLongRunngingScript.py 2>&1 | tee log.txt'' – stephenfin 2013-12-11 10:54:44