Python, how to send output to both file and terminal
Question: I want to use Python to send output to both a file `log.txt` and STDOUT on the
terminal. Here is what I have:

    
    
    import sys
    class Logger(object):
        def __init__(self, filename="Default.log"):
            self.terminal = sys.stdout
            self.log = open(filename, "a")
    
        def write(self, message):
            self.terminal.write(message)
            self.log.write(message)
    
    sys.stdout = Logger("log.txt")
    print "Hello world !"            #This line is saved in log.txt and STDOUT
    

This program sends output to the file and stdout. My question is: How did the
write function to the file get called?


Answer: From the [documentation](http://docs.python.org/2/library/sys.html#sys.stdout)
for sys.stdout:

> stdout and stderr needn’t be built-in file objects: any object is acceptable
> as long as it has a write() method that takes a string argument.

