Python – How to Print to Screen and a File at the Same Time

Question: How can I capture all of my print statements to a file, but still have them shown in the console?

Answer: Read on!

Here’s a little script I put in a file called “Logger.py”.

"""
Capture print statments and write them to a log file
but still allow them to be printed on the screen.
Usage:  see if __name__=='__main__': section below.
"""
import sys
import time

class Logger:
    def __init__(self, stdout, filename):
        self.stdout = stdout
        self.logfile = file(filename, 'a')
        self.logfile.write('\n\nNew run at %s\n\n' % time.ctime())
    def write(self, text):
        self.stdout.write(text)
        self.logfile.write(text)
        self.logfile.flush()
    def close(self):
        """Does this work or not?"""
        self.stdout.close()
        self.logfile.close()

if __name__=='__main__':
    #Usage:
    logger = Logger(sys.stdout, 'log.txt')
    sys.stdout = logger
    print 'this should go on screen and in file'
    print 'this too'
    print

Then to use this, I just put this mess of statements below in my “if __name__==’__main__’” section of each script*. Then every script I run has its console messages nicely saved to a file for me.

import Logger;logger=Logger.Logger(sys.stdout,'log.txt');sys.stdout=logger

Big thanks to the folks on this thread for suggesting this code.

*Best to not put that mess of statements at the top of your script because you’ll get some weird results if another module imports it.

[tags]python, logging, stdout, logfile[/tags]

Comments are closed.