How do you redirect print() output directly to a log or text file in Python? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you redirect print() output directly to a log or text file in Python?

message-square
0

Pass file=f directly to print("message", file=f) inside a with open("output.log", "a", encoding="utf-8") as f: block for selective, per-call file logging, use contextlib.redirect_stdout(f) to capture all print() output across an entire function or third-party call temporarily, or redirect sys.stdout (or shell output python script.py > output.log 2>&1) when routing every print() statement in a script to a file.

Basic Example

from contextlib import redirect_stdout

# 1. Recommended for selective logging: Pass `file=` directly to `print()`
with open("app.log", "a", encoding="utf-8") as f:
    print("Server started on port 8080", file=f)
    print("Connected to database", file=f, flush=True)  # `flush=True` writes immediately to disk

# 2. Capture all `print()` calls inside a block or function (`contextlib.redirect_stdout`):
def generate_report() -> None:
    print("Summary Report")
    print("Total items: 42")

with open("report.txt", "w", encoding="utf-8") as f:
    with redirect_stdout(f):
        generate_report()  # Every `print()` inside here writes to `report.txt`

# 3. Redirect ALL `print()` calls globally for the remainder of the script (`sys.stdout`):
import sys

log_file = open("global_stdout.log", "w", encoding="utf-8")
sys.stdout = log_file
print("This goes straight to global_stdout.log")
sys.stdout = sys.__stdout__  # Restore original terminal stdout before closing
log_file.close()

Key Details & Edge Cases

  • Append ("a") vs. Overwrite ("w") mode and encoding="utf-8":
    • Use mode="a" (append) when accumulating entries in a persistent log file across runs, and mode="w" (write/truncate) when generating a fresh report file on each run. Always specify encoding="utf-8" so Unicode symbols or non-ASCII text never crash on Windows (cp1252).
  • Buffering delay (flush=True or buffering=1):
    • When print(..., file=f) writes to a disk file instead of an interactive terminal, Python buffers output in 4 KB–8 KB chunks in memory before flushing to disk. If your script runs continuously or crashes mid-run, pass flush=True (print("msg", file=f, flush=True)) or open with line buffering (open("app.log", "a", buffering=1, encoding="utf-8")) so every line appears in the file immediately.
  • Always restore sys.stdout = sys.__stdout__ if mutating sys.stdout:
    • If you assign sys.stdout = f globally and close f without restoring sys.__stdout__, any subsequent print() raises ValueError: I/O operation on closed file. Prefer contextlib.redirect_stdout(f) because it restores sys.stdout automatically even if an exception occurs inside the with block.
  • Uncaught tracebacks go to sys.stderr, NOT sys.stdout:
    • Redirecting print() or sys.stdout does not capture print(..., file=sys.stderr) or unhandled exception tracebacks. To capture both standard output and errors, pair redirect_stdout(f) with contextlib.redirect_stderr(f) (or run python app.py >> app.log 2>&1 from the command line).
  • Use Python’s built-in logging module for production application logs:
    • While print(..., file=f) works well for simple scripts and text reports, use logging.basicConfig(filename="app.log", level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") whenever you need timestamps, log levels (INFO/ERROR), thread safety, or automatic log rotation (RotatingFileHandler).

Comparison of print() File-Redirection Methods in Python

Method Scope of Redirection Restores Terminal stdout Automatically? Captures Third-Party print() Calls? Best Used When
print(..., file=f) (Recommended for targeted writes) Single print() statement Yes (sys.stdout is untouched) No (explicit per call) Writing specific lines or reports to a file while keeping normal console output intact.
contextlib.redirect_stdout(f) (Recommended for functions/blocks) Entire with block (including nested calls) Yes (guaranteed on block exit or exception) Yes Capturing stdout from existing functions or third-party libraries into a file or io.StringIO.
sys.stdout = open(...) Entire script from assignment onward No (must manually restore sys.__stdout__) Yes Simple top-to-bottom scripts where every print() should go to a single log file.
Shell redirection (python script.py > out.log 2>&1) Entire process (stdout + stderr) N/A (handled by OS shell) Yes (including C extensions & tracebacks) Cron jobs, background daemons, and CLI runs without modifying Python source code.