sys.stndout syntax

Alex Martelli alex at magenta.com
Fri Aug 18 16:31:30 EDT 2000


"d. savitsky" <dsavitsk at e-coli.net> wrote in message
news:VYen5.7691$ZI2.315853 at news1.rdc1.il.home.com...
> greetings, very quick question.
>
> on win32, to get printed output to a file i use
> >>> sys.stndout = open('file.txt', 'w')
> how do i get it to go back to the command line,

Two options:

a) saveso = sys.stdout
    sys.stdout =  open('file.txt', 'w')

    # blah blah

    sys.stdout = saveso

b) sys.stdout =  open('file.txt', 'w')

    # blah blah

    sys.stdout = sys.__stdout__

Option (b), while slightly simpler, has problems
if _somebody else_ had also redirected output.


> or better yet, how do i
> output to both at the same time?

class tee_redir:
    def __init__(self,*files):
        self.files=files
        self.stdout=sys.stdout
        sys.stdout=self
    def write(self,line):
        for file in self.files:
            file.write(line)
        self.stdout.write(line)
    def close(self):
        for file in self.files:
            file.close()
        sys.stdout = self.stdout

thetee=tee_redir(open('file.txt','w'))

# whatever

thetee.close()


It's a delicate issue whether this class should
take in __init__ the already-open files, or the
filenames (and open them itself) -- I choose
the former as more general (one could also
accept both string-like OR file-like objects, but
that gets a bit complex).

Another design issue is whether this class
should self-install its latest instance as the
sys.stdout; doing so, as I show above, is a
bit inelegant and less than general -- one
could have a more general class tee that
just does the 1-to-N broadcast, and manually
install it as sys.stdout.

But anyway, I think the general idea is clear:
write a file-like object implementing the
write method however you like best, e.g by
delegating it to other file-like objects.


Alex






More information about the Python-list mailing list