python - 如何自动将 print 语句的输出定向到 python 中的文件?

标签 python logging output

我有一个python脚本,它包含print此处和那里的语句用于调试目的。现在我发现很难在控制台中阅读它们。 python是否有任何库可以自动引导所有print语句的输出到指定的文本文件?顺便说一句,我使用 Windows 7,而不是 Linux。我也不从命令行运行我的脚本。

所以我想要的是如下所示:

import logger_module

log_file = "log.txt"
logger_module.activate_logging(log_file)

print "blablabla"

当我运行上面的脚本时,我应该在log.txt中看到“blablabla”文件。

最佳答案

我相信这是您能得到的最接近的结果:

import sys
sys.stdout = open('file', 'w')
print 'test' # prints test to file

如果您想写入多个位置,可以使用以下命令。任何具有 write 方法的对象都可以分配给 python 中的 sys.stdout。

import sys

class Logger(object):
    def __init__(self, *files):
        self.files = files

    def write(self, obj):
        for f in self.files:
            f.write(obj)

f = open('file', 'w')
sys.stdout = Logger(f, sys.stdout)

print "Python Magic"

关于python - 如何自动将 print 语句的输出定向到 python 中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20898212/

相关文章:

java - 触发 SizeBasedTriggeringPolicy 时 Log4j Filepattern 不起作用

c - 在 C 中使用 fread 读取整数时出错

c - C 程序协助 : Solving for Delta

Python 2.7.7 包安装给出 Visual C++ cl.exe 错误 : command failed with exit status 2

python - 关于 np.nonzero(arr)[0] 中 Trailing[0] 的作用的问题

python - 读取 xterm 中的当前文本颜色

python - 如何从 setup.py 中提取依赖信息

Delphi:现场应用程序错误日志记录

java - 捕获 log4j 输出

Linux 将控制台输出写入文件