Traceback module in python

General

It provides a standard interface to extract, format and print stack traces of Python programs.
It mimics the behavior of the Python interpreter when it prints a stack trace.
The module uses traceback objects (of type types.TracebackType), which are assigned to the __traceback__ field of BaseException instances.

Helpful functions

Formal functions:

Print up stack trace entries from traceback object tb:
traceback.print_tb(tb, limit=None, file=None)

– if limit is positive: starting from the caller’s frame
– Otherwise, print the last abs(limit) entries.
– If limit is None, all entries are printed.

Print exception information and stack trace entries from traceback object tb:
traceback.print_exception(exc, /, [value, tb, ]limit=None, file=None, chain=True)

This differs from print_tb() in the following ways:
– if tb is not None, it prints a header Traceback (most recent call last).
– it prints the exception type and value after the stack trace

Variant of the traceback.print_tb() function that starts from the invocation point:
traceback.print_stack(f=None, limit=None, file=None)

Shorthand functions:

Shorthand for print_exception(sys.exception(), limit, file, chain):
traceback.print_exc(limit=None, file=None, chain=True)

Like print_exc(limit) but returns a string instead of printing to a file:
traceback.format_exc(limit=None, chain=True)

Examples

Print tracebacks or exceptions

source code:

import traceback
from time import sleep
 
 
def print_tb():
    print(f'print_tb()', flush=True)
    try:
        invalid = 'a'[1]
    except Exception as e:
        traceback.print_tb(e.__traceback__)
 
 
def print_exception():
    print(f'print_exception()', flush=True)
    try:
        invalid = 'a'[1]
    except Exception as e:
        traceback.print_exception(e)
 
 
def print_exc_shorthand_for_print_exception():
    print(f'print_exc_shorthand_for_print_exception()', flush=True)
    try:
        invalid = 'a'[1]
    except Exception as e:
        traceback.print_exc()
 
 
def print_exception_with_format_exc():
    print(f'print_exception_with_format_exc()', flush=True)
    try:
        invalid = 'a'[1]
    except Exception as e:
        print(traceback.format_exc())
 
 
if __name__ == '__main__':
    print_exception()
    sleep(0.5)
    print(f'----------', flush=True)
    # shorthand for print_exception(sys.exception())
    print_exc_shorthand_for_print_exception()
    sleep(0.5)
    print(f'----------', flush=True)
    print_exception_with_format_exc()
    sleep(0.5)
    print(f'----------', flush=True)
    print_tb()
    sleep(0.5)
    print(f'----------', flush=True)

Output:

print_exception()
Traceback (most recent call last):
  File "C:\programmation\workspace-python\python_blog_examples\traceback\print_tb_example.py", line 16, in print_exception
    invalid = 'a'[1]
IndexError: string index out of range
----------
print_exc_shorthand_for_print_exception()
Traceback (most recent call last):
  File "C:\programmation\workspace-python\python_blog_examples\traceback\print_tb_example.py", line 24, in print_exc_shorthand_for_print_exception
    invalid = 'a'[1]
IndexError: string index out of range
----------
print_exception_with_format_exc()
Traceback (most recent call last):
  File "C:\programmation\workspace-python\python_blog_examples\traceback\print_tb_example.py", line 32, in print_exception_with_format_exc
    invalid = 'a'[1]
IndexError: string index out of range
 
----------
print_tb()
  File "C:\programmation\workspace-python\python_blog_examples\traceback\print_tb_example.py", line 8, in print_tb
    invalid = 'a'[1]
----------
 
Process finished with exit code 0

Print the stacks of all running threads thanks to print_stack()

Source code:

import sys
import threading
import traceback
from threading import Thread
from time import sleep
 
 
def a():
    i: int = 0
    while True:
        i += 1
        sleep(0.25)
 
 
def b():
    sleep(5)
 
 
Thread(daemon=True, name='a', target=lambda: a()).start()
Thread(daemon=True, name='b', target=lambda: b()).start()
for th in threading.enumerate():
    print(th, flush=True)
    traceback.print_stack(sys._current_frames()[th.ident])
    # The sleep is required to get an output as expected, otherwise the print_stack() outputs are 
    # merged. 
    sleep(0.5)
    print('---------------------', flush=True)
    sleep(0.5)
sys.exit()

Output:

C:\Users\david\AppData\Local\Programs\Python\Python310\python.exe C:/programmation/workspace-python/python_blog_examples/traceback/print_stack_of_all_threads.py
<_MainThread(MainThread, started 20232)>
  File "C:\programmation\workspace-python\python_blog_examples\traceback\print_stack_of_all_threads.py", line 23, in <module>
    traceback.print_stack(sys._current_frames()[th.ident])
---------------------
<Thread(a, started daemon 3712)>
  File "C:\Users\david\AppData\Local\Programs\Python\Python310\lib\threading.py", line 973, in _bootstrap
    self._bootstrap_inner()
  File "C:\Users\david\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "C:\Users\david\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "C:\programmation\workspace-python\python_blog_examples\traceback\print_stack_of_all_threads.py", line 19, in <lambda>
    Thread(daemon=True, name='a', target=lambda: a()).start()
  File "C:\programmation\workspace-python\python_blog_examples\traceback\print_stack_of_all_threads.py", line 12, in a
    sleep(0.25)
	---------------------
<Thread(b, started daemon 18128)>
  File "C:\Users\david\AppData\Local\Programs\Python\Python310\lib\threading.py", line 973, in _bootstrap
    self._bootstrap_inner()
  File "C:\Users\david\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "C:\Users\david\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "C:\programmation\workspace-python\python_blog_examples\traceback\print_stack_of_all_threads.py", line 20, in <lambda>
    Thread(daemon=True, name='b', target=lambda: b()).start()
  File "C:\programmation\workspace-python\python_blog_examples\traceback\print_stack_of_all_threads.py", line 16, in b
    sleep(5)
---------------------
 
Process finished with exit code 0
Ce contenu a été publié dans Non classé. Vous pouvez le mettre en favoris avec ce permalien.

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *