Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, logging print statements while having them print to stdout

I have a long python script that uses print statements often, I was wondering if it was possible to add some code that would log all of the print statements into a text file or something like that. I still want all of the print statements to go to the command line as the user gets prompted throughout the program. If possible logging the user's input would be beneficial as well.

I found this which somewhat answers my question but makes it where the "print" statement no longer prints to the command line

Redirect Python 'print' output to Logger

like image 200
shreddish Avatar asked Jul 25 '13 19:07

shreddish


1 Answers

You can add this to your script:

import sys
sys.stdout = open('logfile', 'w')

This will make the print statements write to logfile.

If you want the option of printing to stdout and a file, you can try this:

class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)

f = open('logfile', 'w')
backup = sys.stdout
sys.stdout = Tee(sys.stdout, f)

print "hello world"  # this should appear in stdout and in file

To revert to just printing to console, just restore the "backup"

sys.stdout = backup
like image 115
jh314 Avatar answered Nov 15 '22 13:11

jh314