redirecting stdout to a file as well as screen

Ant antroy at gmail.com
Thu Apr 12 03:40:41 EDT 2007


On Apr 12, 8:14 am, "SamG" <mad.vi... at gmail.com> wrote:
> How could i make, from inside the program, to have the stdout and
> stderr to be printed both to a file as well the terminal(as usual).

One way would be to create a custom class which has the same methods
as the file type, and held a list of file-like objects to write to.
e.g.

class multicaster(object):
    def __init__(self, filelist):
        self.filelist = filelist

    def write(self, str):
        for f in self.filelist:
            f.write(str)
    def writelines(self, str_list):
        #etc

Then assign stdout and stderr to a new instance of one of these
objects:

mc = multicaster([sys.stdout, sys.stderr, log_file])
sys.stdout = mc
sys.stderr = mc

HTH





More information about the Python-list mailing list