How do I redirect output to a file and to the console screen?

Martin Miller ggrp1.20.martineau at dfgh.net
Wed Dec 28 14:01:16 EST 2005


The basic way to redirect output is to reassign a value to sys.stdout
-- something along these lines:

    # redirect stdout to a disk file
    import sys
    saveout = sys.stdout
    outfile = open('output.txt', 'w')
    sys.stdout = outfile

    # output stuff
    print 'hello world'

    # restore stdout
    outfile.flush()
    outfile.close()
    sys.stdout = saveout:

Essentially what you want is to have output redirected to *two*
different streams at the same time, the original stdout and a file.
Here's a link to a (very old) post on the subject that should help (see
'class Tee') if coupled with the above:

> http://groups.google.com/group/comp.lang.python/msg/5ab52448c1cbc10e

-Martin




More information about the Python-list mailing list