Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, how to send output to both file and terminal

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?

like image 850
user192082107 Avatar asked Feb 22 '13 08:02

user192082107


People also ask

How do I send console output to a file?

To redirect the output of a command to a file, type the command, specify the > or the >> operator, and then provide the path to a file you want to the output redirected to. For example, the ls command lists the files and folders in the current directory.

Which function print the output to the console in Python?

The simplest way to write to the console or visual display is python's print function. When the print statement in the script was executed, the string 'Hello, world!'


2 Answers

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.

like image 54
Zitrax Avatar answered Sep 30 '22 06:09

Zitrax


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.

like image 45
Markon Avatar answered Oct 01 '22 06:10

Markon