rich/docs/source/traceback.rst

76 lines
2.5 KiB
ReStructuredText
Raw Normal View History

2020-02-22 20:04:20 +00:00
Traceback
=========
2021-08-03 16:27:42 +00:00
Rich can render Python tracebacks with syntax highlighting and formatting. Rich tracebacks are easier to read and show more code than standard Python tracebacks.
To see an example of a Rich traceback, running the following command::
python -m rich.traceback
2020-02-22 20:04:20 +00:00
Printing tracebacks
-------------------
2020-02-22 20:14:23 +00:00
The :meth:`~rich.console.Console.print_exception` method will print a traceback for the current exception being handled. Here's an example::
2020-02-22 20:04:20 +00:00
2021-08-03 16:27:42 +00:00
from rich.console import Console
console = Console()
2020-02-22 20:04:20 +00:00
try:
do_something()
2021-08-03 16:27:42 +00:00
except Exception:
console.print_exception(show_locals=True)
2020-02-22 20:04:20 +00:00
2021-08-03 16:27:42 +00:00
The ``show_locals=True`` parameter causes Rich to display the value of local variables for each frame of the traceback.
See `exception.py <https://github.com/willmcgugan/rich/blob/master/examples/exception.py>`_ for a larger example.
2020-02-22 20:04:20 +00:00
Traceback handler
-----------------
Rich can be installed as the default traceback handler so that all uncaught exceptions will be rendered with highlighting. Here's how::
from rich.traceback import install
install(show_locals=True)
2020-03-08 18:34:56 +00:00
There are a few options to configure the traceback handler, see :func:`~rich.traceback.install` for details.
2021-09-24 08:41:23 +00:00
Suppressing Frames
------------------
2021-09-24 09:02:56 +00:00
If you are working with a framework (click, django etc), you may only be interested in seeing the code from your own application within the traceback. You can exclude framework code by setting the `suppress` argument on `Traceback`, `install`, and `Console.print_exception`, which should be a list of modules or str paths.
2021-09-24 08:41:23 +00:00
2021-10-06 13:07:20 +00:00
Here's how you would exclude `click <https://click.palletsprojects.com/en/8.0.x/>`_ from Rich exceptions::
2021-09-24 08:41:23 +00:00
import click
from rich.traceback import install
install(suppress=[click])
Suppressed frames will show the line and file only, without any code.
Max Frames
----------
A recursion error can generate very large tracebacks that take a while to render and contain a lot of repetitive frames. Rich guards against this with a `max_frames` argument, which defaults to 100. If a traceback contains more than 100 frames then only the first 50, and last 50 will be shown. You can disable this feature by setting `max_frames` to 0.
Here's an example of printing an recursive error::
from rich.console import Console
def foo(n):
return bar(n)
def bar(n):
return foo(n)
console = Console()
try:
foo(1)
except Exception:
console.print_exception(max_frames=20)