7

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?

2 Answers 2

3

From the documentation 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.

Sign up to request clarification or add additional context in comments.

Comments

2

More specifically, the print function (in Python 2.X it is still a keyword, but it doesn't matter here) does something like this

import sys
def print(message):
    sys.stdout.write(message)

so that, when you call it it will print your message on sys.stdout. However, if you overwrite sys.stdout with an object containing a .write method, well, it will call that method. That's the magic of duck-typing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.