[Python] Printing to screen and writing to a file at the same time

Discussão em 'Python' iniciado por Stack, Abril 18, 2025.

  1. Stack

    Stack Membro Participativo

    I found some code online that generally works, but I want to use it multiple times in the same program (write different things to different files, while still printing to the screen the whole time).

    That is to say, when it closes, I think sys.stdout closes, so printing at all, and using this class again fails. I tried reimporting sys, and other dumb stuff, but I can't get it to work.

    Here's the site, and the code groups.google.com/group/comp.lang.python/browse_thread/thread/d25a9f5608e473af/

    import sys

    class MyWriter:

    def __init__(self, stdout, filename):
    self.stdout = stdout
    self.logfile = file(filename, 'a')

    def write(self, text):
    self.stdout.write(text)
    self.logfile.write(text)

    def close(self):
    # self.stdout.close()
    self.logfile.close()

    writer = MyWriter(sys.stdout, 'log.txt')
    sys.stdout = writer

    print 'test'

    Continue reading...

Compartilhe esta Página