Python traceback - print or capture exception stack traces as strings
Answer: The traceback module provides a standard interface to extract, format and print stack traces. print_exc() prints the exception being handled, and format_exc() is like it but returns a string instead of printing to a file. Use format_exception(exc) for any exception object and TracebackException to capture one for later rendering.
Examples
import sys
import traceback
try:
1 / 0
except ZeroDivisionError as exc:
traceback.print_exc() # to sys.stderr
text = traceback.format_exc() # same text as a str
lines = traceback.format_exception(exc) # list of str
traceback.print_exc(limit=1, file=sys.stdout)
saved = traceback.TracebackException.from_exception(exc)
print("".join(saved.format()))
traceback.print_stack(limit=3) # where am I now?
Functions
| Function | What it does | |---|---| | print_exc(limit=None, file=None, chain=True) | shorthand for print_exception(sys.exception(), ...) | | format_exc() | like print_exc() but returns a string | | print_exception(exc) | prints the Traceback (most recent call last): header, entries, then the exception type and value | | format_exception(exc) | a list of strings, each ending in a newline; joined, they match print_exception() | | print_stack(limit=None) | prints stack trace entries from the invocation point |
Arguments
limitprints up to that many entries if positive; otherwise the lastabs(limit)entries.Noneprints all of them.filedefaults tosys.stderrwhen omitted orNone.chain=Truealso prints chained exceptions (__cause__and__context__).
TracebackException
TracebackException captures enough information about an exception to print it later, without keeping a reference to the actual exception. Exceptions can be the roots of large object graphs, so this can significantly improve memory management.
Related
Traceback objects are assigned to the __traceback__ field of exceptions. The faulthandler module dumps Python tracebacks on a fault, after a timeout, or on a user signal.
See also
Claims
- id: C1 claim: format_exc returns a string instead of printing. source: S1 evidence: "This is like print_exc(limit) but returns a string instead of printing to a file."
- id: C2 claim: TracebackException can improve memory management. source: S1 evidence: "this utility can significantly improve memory management."
- id: C3 claim: print_exc is shorthand for print_exception with sys.exception(). source: S2 evidence: "Shorthand for 'print_exception(sys.exception(), limit=limit, file=file, chain=chain)'."
Sources
- [S1] traceback - Print or retrieve a stack traceback. Python docs. https://docs.python.org/3/library/traceback.html . License: PSF-2.0. Accessed 2026-11-18.
- [S2] Lib/traceback.py. python/cpython (GitHub). https://github.com/python/cpython/blob/main/Lib/traceback.py . License: PSF-2.0. Accessed 2026-11-18.
License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, traceback - Print or retrieve a stack traceback; python/cpython (GitHub), Lib/traceback.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.
License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, traceback - Print or retrieve a stack traceback; python/cpython (GitHub), Lib/traceback.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.
Cite this
iinventedlight. 2026. "Python traceback - print or capture exception stack traces as strings." iinventedlight Library, iil:note:h3qqf4cr, version of 2026-11-18. https://iinventedlight.com/library/notes/python-traceback/. License: CC-BY-4.0.
@misc{iil_note_h3qqf4cr,
author = {{iinventedlight}},
title = {{Python traceback - print or capture exception stack traces as strings}},
howpublished = {iinventedlight Library},
year = {2026},
date = {2026-11-18},
url = {https://iinventedlight.com/library/notes/python-traceback/},
note = {Permanent ID iil:note:h3qqf4cr. License: CC-BY-4.0.},
}
Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).
Extra files beside this note
These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.
- python-traceback.table.json (table; CC-BY-4.0)
- python-traceback.schema.json (schema; CC-BY-4.0)
For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-traceback.md.