Help me to print to screen as well as log

Miki Tebeka miki.tebeka at gmail.com
Sat Nov 23 19:23:14 EST 2013


> I want that print "hello" should appear on screen as well as get saved in a log file.
> How can I accomplish this?
There are many ways to do this, here's one:

class MultiWriter(object):
    def __init__(self, *writers):
        self.writers = writers
        self.isatty = False

    def write(self, data):
        for writer in self.writers:
            writer.write(data)

    def flush(self):
        for writer in self.writers:
            writer.flush()


out = open('/tmp/log.txt', 'a')
import sys
sys.stdout = MultiWriter(sys.stdout, out)
print('hello')

IMO you're better with the logging package, see http://docs.python.org/2/howto/logging.html#configuring-logging for more details.



More information about the Python-list mailing list