Categories
Python Answers

How to duplicate sys.stdout to a log file with Python?

Spread the love

Sometimes, we want to duplicate sys.stdout to a log file with Python.

In this article, we’ll look at how to duplicate sys.stdout to a log file with Python.

How to duplicate sys.stdout to a log file with Python?

To duplicate sys.stdout to a log file with Python, we can create our own logger class.

For instance, we write

import sys

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open("log.dat", "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)  

sys.stdout = Logger()

print("%d %d" % (1, 2))

to create the Loffer class that has the write method to write message to the terminal with self.terminal.write.

And we write message to the log file with self.log.write.

Then we set sys.stdout to a Logger instance.

Now when we call print, the argument’s value should be printed to the screen and appended to the log.

Conclusion

To duplicate sys.stdout to a log file with Python, we can create our own logger class.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *