Redirecting standard output from Python: another example

I wrote a previous post about how to redirect standard output from a Python script to a GUI window.  In this post, I will give an even simpler example of to redirect standard output to a log file.  During the early development and debugging of Python programs, I use print statements to keep me informed of what’s happening.  However, printing to the terminal is not always practical–for example, when I run numerical code on a parallel cluster, there is no way to determine which output came from which instance of the program.  Here is a class that you can use to redirect standard output to a log file:

class Logger:
    """The Logger class can be used to redirect standard output to a log file.
    Usage: Create a Logger object and redirect standard output to the Logger 
    object.  For example:
    output = Logger(file_handle, True)
    import sys
    sys.stdout = output

    def __init__(self, logFile, echo):
        logFile     a file object that is available for writing
        echo        Boolean.  If True, output is sent to standard output in
                    addition to the log file. 
        import sys
        self.out = sys.stdout
        self.logFile = logFile
        self.echo = echo

    def write(self, s):
        """Required method that replaces stdout. You don't have to call this
        directly--all print statements will be redirected here."""
        if self.echo:

I create a Logger object and pass it as an optional keyword parameter to an object that produces output that I want to redirect.  The __init__ method of that object looks something like this:

    def __init__(... , output=None):
        if output is not None:
            print "Redirecting output..."
            import sys
            sys.stdout = output

You should be able to make use of this class “as is.”  It would be a little more robust if it checked whether the file object was available for writing–feel free to improve upon it.

Leave a Reply