Nov 30 2009

Python Log Stdout to File

xiao

Python has the ability to alter its sys.stdout as to redirect its print commands to pretty much anything.

If, for instance, you want to print to both standard output and to a log file, you can create a class to handle the stdout like such:

class MyOutput():
    def __init__(self, logfile):
        self.stdout = sys.stdout
        self.log = open(logfile, 'w')
 
    def write(self, text):
        self.stdout.write(text)
        self.log.write(text)
        self.log.flush()
 
    def close(self):
        self.stdout.close()
        self.log.close()
 
sys.stdout = MyOutput("log.txt")
print "blah blah blah"

Continue reading