Redirecting Python Standard Output to a Text File
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.