Can we use print to print to more than sys.stdout?

Jason Orendorff jason at jorendorff.com
Tue Mar 12 13:25:09 EST 2002


Pierre Rouleau wrote:
> #1) Is it possible to change print behavior to make it print to several
> streams?
>
> #2)
> Is it also possible to define an object that would behave like a file
> and that would do the printing itself to wherever required?

# Sure.  This code does both.

class Mux:
    def __init__(self, *objects):
        self.__objects = objects
    def write(self, data):
        for obj in self.__objects:
            obj.write(data)
    def writelines(self, lines):
        for obj in self.__objects:
            obj.writelines(lines)

myfile = open('somefile.txt', 'a')
sys.stdout = Mux(sys.stdout, myfile)

## Jason Orendorff    http://www.jorendorff.com/






More information about the Python-list mailing list