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 andencoding="utf-8":- Use
mode="a"(append) when accumulating entries in a persistent log file across runs, andmode="w"(write/truncate) when generating a fresh report file on each run. Always specifyencoding="utf-8"so Unicode symbols or non-ASCII text never crash on Windows (cp1252).
- Use
- Buffering delay (
flush=Trueorbuffering=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, passflush=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.
- When
- Always restore
sys.stdout = sys.__stdout__if mutatingsys.stdout:- If you assign
sys.stdout = fglobally and closefwithout restoringsys.__stdout__, any subsequentprint()raisesValueError: I/O operation on closed file. Prefercontextlib.redirect_stdout(f)because it restoressys.stdoutautomatically even if an exception occurs inside thewithblock.
- If you assign
- Uncaught tracebacks go to
sys.stderr, NOTsys.stdout:- Redirecting
print()orsys.stdoutdoes not captureprint(..., file=sys.stderr)or unhandled exception tracebacks. To capture both standard output and errors, pairredirect_stdout(f)withcontextlib.redirect_(f)(or runpython app.py >> app.log 2>&1from the command line).
- Redirecting
- Use Python’s built-in
loggingmodule for production application logs:- While
print(..., file=f)works well for simple scripts and text reports, uselogging.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).
- While
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. |
You must log in or register to comment.
