The traceback
module in Python provides a standardized interface to extract, format, and print stacktraces.
The print_tb
method of the traceback
module prints the stacktraces from the traceback
object up to a limit.
Here’s the syntax for traceback.print_tb()
method:
traceback.print_tb(tb, limit=None, file=None)
Here are the parameters of the traceback.print_tb()
method:
tb
: This is the traceback object.limit
: This parameter can be used to specify the amount of trace required. The default value is None
and will print the whole stacktrace. When limit
is a negative value, the abs(limit)
is taken into consideration.file
: This parameter indicates where the stacktrace output should be directed to. The default value is None
and the output goes to the standard error.import tracebackdef func_2():print("hello educative")raise Exception("")def func_1():func_2()print("Printing complete stacktrace:")try:func_1()except Exception as e:traceback.print_tb(e.__traceback__)print("-" * 8)print("Printing upto 2 stacktraces:")try:func_1()except Exception as e:traceback.print_tb(e.__traceback__, limit=2)
traceback
module.func_2()
function is defined where it throws an exception.func_1()
function is defined. This invokes func_2()
.func_1()
is invoked, and the complete stacktrace is printed.func_1()
is invoked, and the stacktrace up to level 2 is printed. We do this using the limit
parameter of the print_tb()
function.