Python - 自动将所有打印语句写入日志文件

时间:2017-05-16 16:25:52

标签: python logging printing

我有一个脚本,在此过程中包含大量的打印语句,这是一个例子:

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])

...

那么我可以将所有打印语句放在日志文件中吗?

2 个答案:

答案 0 :(得分:3)

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.

答案 1 :(得分:0)

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

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

相关问题