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

tha*_*eow 1 python printing logging

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

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

...
Run Code Online (Sandbox Code Playgroud)

那么有没有一种方法可以将所有打印语句放入日志文件中?

Pet*_*ood 5

替换stdout为您的日志文件:

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

import pandas

print "pandas library imported"
df = pd.Dataframe(...)
print "df created."
Run Code Online (Sandbox Code Playgroud)

输出log.txt

pandas library imported
df created.
Run Code Online (Sandbox Code Playgroud)