Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Redirecting Python Standard Output to a Text File

Notes May 14 72

Command-Line Redirection Operators

Standard shell syntax provides the quickest method for capturing script output during execution. The single greater-than symbol (>) overwrites any existing target document, while the double symbol (>>) appends new data without altering previous entries.

# process_data.py
for idx in range(50):
    print(f"Record {idx} processed successfully")

Execution examples:

# Overwrite existing log
python process_data.py > execution_results.txt
# Append to existing log
python process_data.py >> execution_results.txt

Direct Standard Output Stream Assignment

Modifying the sys.stdout reference allows the interpreter to route all subsequent output directly into a file descriptor. This technique effectively silences the terminal while capturing every print statement.

import sys

output_path = "stream_capture.txt"
log_descriptor = open(output_path, "w")
try:
    sys.stdout = log_descriptor
    for step in range(1, 6):
        print(f"Step {step} completed successfully.")
finally:
    sys.stdout = sys.__stdout__
    log_descriptor.close()

Targeted File Parameter Routing

The built-in print function accepts a file keyword argument, enabling explicit control over output destinations. By invoking print twice with different targets, developers can achieve simultaneous terminal display and disk persistence.

import sys
import time

disk_destination = open("dual_output.txt", "w")
try:
    for item in range(3):
        message = f"Item value: {item ** 3}"
        print(message, file=disk_destination, flush=True)
        print(message, file=sys.stdout)
        time.sleep(0.2)
finally:
    disk_destination.close()

Enabling flush=True forces immediate disk writes, bypassing internal buffering to ensure real-time logging.

Custom Stream Interception Class

Implementing a lightweight wrapper that intercepts standard stream calls allows automatic duplication across multiple channels without modifying individual print statements.

import sys

class DualLogger:
    def __init__(self, filepath, terminal=sys.stdout):
        self.destination_file = open(filepath, "a")
        self.primary_console = terminal

    def write(self, text_chunk):
        self.primary_console.write(text_chunk)
        self.destination_file.write(text_chunk)
        self.primary_console.flush()
        self.destination_file.flush()

    def flush(self):
        pass

sys.stdout = DualLogger("class_based_log.txt")
print("Initialization complete")
print("Monitoring system metrics...")

External Tee Utilities

Unix-like operating systems ship with the tee utility, which reads from standard input and duplicates data to both a specified file and standard output. Windows environments require external binaries like UnxUtils, placing tee.exe within the system PATH.

python application.py | tee runtime.log

To maintain previous entries instead of overwriting them:

python application.py | tee -a runtime.log

For legacy Windows configurations lacking native support, combining output redirection with file monitoring tools achieves similar behavior, though true parallel console display typically requires third-party packages or PowerShell equivalents like Tee-Object.

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Collecting Disk Capacity and Free Space Metrics in SQL Server

Monitoring storage consumption is a routine operational task. SQL Server exposes several way to inspect disk space, ranging from quick checks to more complete inventories that include total capacity....

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.