1

I have a scripts that contains lots of print statements along the process, here is an example:

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

...

So is there a way that I can put all the print statements in a log file?

DanZimmerman
  • 1,626
  • 6
  • 23
  • 45
  • Possible duplicate of [Python, logging print statements while having them print to stdout](http://stackoverflow.com/questions/17866724/python-logging-print-statements-while-having-them-print-to-stdout) – Peter Wood May 16 '17 at 16:34

2 Answers2

5

Replace stdout with your log file:

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

import pandas

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

Output log.txt:

pandas library imported
df created.
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
0

Use from __future__ import print_function and call print with the file keyword-argument.

Alternatively, redirect the output of your script to a file in your shell.

timgeb
  • 76,762
  • 20
  • 123
  • 145