user
In Python how to copy output to both file and console ?
alphonsio

You can use Python's tee functionality with the sys module to copy output to both the console and a file. Here are a few ways to do it:

1. Using tee-like behavior with sys.stdout

You can create a custom class that writes to both sys.stdout and a file.

import sys

class Tee:
    def __init__(self, filename, mode="w"):
        self.file = open(filename, mode)
        self.stdout = sys.stdout  # Save the original stdout

    def write(self, message):
        self.stdout.write(message)  # Print to console
        self.file.write(message)    # Write to file

    def flush(self):
        self.stdout.flush()
        self.file.flush()

# Redirect stdout to both console and file
sys.stdout = Tee("output.txt")

# Test
print("This will go to both console and file.")

# Reset stdout to default
sys.stdout = sys.__stdout__

2. Using subprocess and tee Command (Linux/Mac)

If running from a terminal, you can use tee directly:

python script.py | tee output.txt

This sends the output to both the terminal and output.txt.


3. Using logging Module

If you are logging output instead of using print, you can use Python’s logging module:

import logging

# Configure logging to write to both file and console
logging.basicConfig(level=logging.INFO,
                    format='%(message)s',
                    handlers=[logging.StreamHandler(), logging.FileHandler("output.log")])

# Example usage
logging.info("This message goes to both console and file.")

Which method you use depends on whether you need print output, logging, or command-line execution.

Let me know if you need more details! 🚀