Python,在将打印语句打印到标准输出的同时记录打印语句 [英] Python, logging print statements while having them print to stdout

查看:336
本文介绍了Python,在将打印语句打印到标准输出的同时记录打印语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的python脚本,该脚本经常使用打印语句,我想知道是否可以添加一些将所有打印语句记录到文本文件或类似文件中的代码.我仍然希望所有打印语句都进入命令行,因为在整个程序中都会提示用户.如果可能的话,记录用户的输入也将是有益的.

I have a long python script that uses print statements often, I was wondering if it was possible to add some code that would log all of the print statements into a text file or something like that. I still want all of the print statements to go to the command line as the user gets prompted throughout the program. If possible logging the user's input would be beneficial as well.

我发现这个问题在某种程度上回答了我的问题,但使"print"语句不再打印到命令行了

I found this which somewhat answers my question but makes it where the "print" statement no longer prints to the command line

将Python打印"输出重定向到Logger

推荐答案

您可以将其添加到脚本中:

You can add this to your script:

import sys
sys.stdout = open('logfile', 'w')

这将使打印语句写入logfile.

如果要选择打印到stdout和文件的选项,可以尝试以下操作:

If you want the option of printing to stdout and a file, you can try this:

class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)

f = open('logfile', 'w')
backup = sys.stdout
sys.stdout = Tee(sys.stdout, f)

print "hello world"  # this should appear in stdout and in file

要恢复为仅打印到控制台,只需还原备份"

To revert to just printing to console, just restore the "backup"

sys.stdout = backup

这篇关于Python,在将打印语句打印到标准输出的同时记录打印语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆