900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > python中把输出结果写到一个文件中_如何将脚本输出写入文件和命令行?

python中把输出结果写到一个文件中_如何将脚本输出写入文件和命令行?

时间:2023-03-05 15:12:49

相关推荐

python中把输出结果写到一个文件中_如何将脚本输出写入文件和命令行?

你看不到任何东西的事实可能与缓冲正在发生的事实有关。所以你只能得到每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)都会刷新到标准输出和指定文件。可能需要调整,因为我还没有测试这个实现。

当然,在打印消息时会看到(大多数情况下很小的)性能损失。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。