【问题标题】:Python - Automatically writing all print statements to a log filPython - 自动将所有打印语句写入日志文件
【发布时间】:2017-05-16 16:25:52
【问题描述】:

我有一个包含大量打印语句的脚本,这是一个示例:

import pandas
print "pandas library imported"
df = pd.Dataframe(...)
print "df created."

print "There are {0} rows and {1} columns in the data frame".format(df.shape[0], df.shape[1])

...

那么有没有办法可以将所有打印语句放在一个日志文件中?

【问题讨论】:

标签: python logging printing


【解决方案1】:

stdout 替换为您的日志文件:

import sys
sys.stdout = open('log.txt', 'r')

import pandas

print "pandas library imported"
df = pd.Dataframe(...)
print "df created."

输出log.txt:

pandas library imported
df created.

【讨论】:

  • 谢谢彼得。这种方式在运行进程时隐藏了所有的打印语句,有没有办法我仍然可以在命令行上打印出消息?
  • @thatMeow 查看上面链接副本的答案
【解决方案2】:

使用from __future__ import print_function 并使用file 关键字参数调用print

或者,将脚本的输出重定向到 shell 中的文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 2018-08-28
    相关资源
    最近更新 更多