Prerequisite: Python Traceback
To print stack trace for an exception the suspicious code will be kept in the try block and except block will be employed to handle the exception generated. Here we will be printing the stack trace to handle the exception generated. The printing stack trace for an exception helps in understanding the error and what went wrong with the code. Not just this, the stack trace also shows where the error occurred.
The general structure of a stack trace for an exception:
- Traceback for the most recent call.
- Location of the program.
- Line in the program where the error was encountered.
- Name of the error: relevant information about the exception.
Example:
Traceback (most recent call last): File "C:/Python27/hdg.py", line 5, in value=A[5] IndexError: list index out of range
Method 1: By using print_exc() method.
This method prints exception information and stack trace entries from traceback object tb to file.
Syntax: traceback.print_exc(limit=None, file=None, chain=True)
Parameters: This method accepts the following parameters:
- if a limit argument is positive, Print up to limit stack trace entries from traceback object tb (starting from the caller’s frame). Otherwise, print the last abs(limit) entries. If the limit argument is None, all entries are printed.
- If the file argument is None, the output goes to sys.stderr; otherwise, it should be an open file or file-like object to receive the output.
- If chain argument is true (the default), then chained exceptions will be printed as well, like the interpreter itself does when printing an unhandled exception.
Return: None.
Code:
Python3
import
traceback
A
=
[
1
,
2
,
3
,
4
]
try
:
value
=
A[
5
]
except
:
traceback.print_exc()
print
(
"end of program"
)
Output:
Traceback (most recent call last): File "C:/Python27/hdg.py", line 8, in value=A[5] IndexError: list index out of range end of program
Method 2: By using print_exception() method.
This method prints exception information and stack trace entries from traceback object tb to file.
Syntax : traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True)
Parameters: This method accepts the following parameters:
- if tb argument is not None, it prints a header Traceback (most recent call last):
- it prints the exception etype and value after the stack trace
- if type(value) argument is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret indicating the approximate position of the error.
- if a limit argument is positive, Print up to limit stack trace entries from traceback object tb (starting from the caller’s frame). Otherwise, print the last abs(limit) entries. If the limit argument is None, all entries are printed.
- If the file argument is None, the output goes to sys.stderr; otherwise, it should be an open file or file-like object to receive the output.
- If chain argument is true (the default), then chained exceptions will be printed as well, like the interpreter itself does when printing an unhandled exception.
Return: None.
Code:
Python3
import
traceback
import
sys
a
=
4
b
=
0
try
:
value
=
a
/
b
except
:
traceback.print_exception(
*
sys.exc_info())
print
(
"end of program"
)
Output:
Traceback (most recent call last): File "C:/Python27/hdg.py", line 10, in value=a/b ZeroDivisionError: integer division or modulo by zero end of program
Печать или вывод в файл информации об исключениях и записей трассировки стека.
Содержание:
traceback.print_tb()
-печать трассировки стека,traceback.print_exception()
— печать исключения и трассировку стека,traceback.print_exc()
— сокращение для вызоваtraceback.print_exception()
,traceback.print_last()
— еще одно сокращение для вызоваprint_exception()
,traceback.print_stack()
— печатает записи трассировки, начиная с точки вызова,-
traceback.format_exc()
— похожа наtraceback.print_exc(limit)
но возвращает строку вместо печати, - Примеры использования вывода на печать исключений и трассировки стека.
traceback.print_tb(tb, limit=None, file=None)
:
Функция traceback.print_tb()
если аргумент limit
положительный, то печатает записи трассировки стека из объекта трассировки tb
, ограничивая количество записей значением limit
(начиная с кадра вызывающего абонента). В противном случае выводит последние записи abs(limit)
.
- Если аргумент
limit
опущен или отсутствует, то печатаются все записи. - Если аргумент файла
file
опущен или отсутствует, то вывод идет вsys.stderr
. - Если аргумент файла
file
задан, то для получения вывода он должен быть открытым файлом или файлоподобным объектом.
traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True)
:
Функция traceback.print_exception()
выводит информацию об исключении и записи трассировки стека из объекта трассировки tb
в файл.
Поведение traceback.print_exception()
отличается от traceback.print_tb()
следующим образом:
- Если
tb
не равноNone
, то выводится заголовокTraceback (most recent call last):
, - Функция печатает
etype
исключения и значение после трассировки стека, - Если
type(value)
— этоSyntaxError
, а значение имеет соответствующий формат, то функция печатает строку, в которой произошла синтаксическая ошибка с символом вставки, указывающим приблизительное положение ошибки.
Необязательный аргумент limit
имеет то же значение, что и в функции traceback.print_tb()
.
Если аргумент chain=True
(по умолчанию), то связанные исключения (атрибуты исключения __cause__
или __context__
) также будут выведены, как это делает сам интерпретатор при печати необработанного исключения.
traceback.print_exc(limit=None, file=None, chain=True)
:
Функция traceback.print_exc()
представляет собой сокращенное название для вызова traceback.print_exception()
и вызывается с параметрами:
traceback.print_exception(*sys.exc_info(), limit, file, chain)
, что значение аргументов etype
, value
и tb
функции traceback.print_exception()
уже подставлены в виде вызова sys.exc_info()
.
traceback.print_last(limit=None, file=None, chain=True)
:
Функция traceback.print_last()
представляет собой сокращенный для вызова traceback.print_exception()
и вызывается с параметрами:
traceback.print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain)
Как правило, функция будет работать только после того, как исключение достигнет интерактивной подсказки (подробнее смотрите описание sys.last_type
).
, что значение аргументов etype
, value
и tb
функции traceback.print_exception()
уже подставлены в виде значений sys.last_type
, sys.last_value
и sys.last_traceback
соответственно.
traceback.print_stack(f=None, limit=None, file=None)
:
Функция traceback.print_stack()
если limit
является положительным, то печатает записи трассировки стека, начиная с точки вызова, ограничивая количество значением limit
. В противном случае выводит на печать последние записи abs(limit)
.
- Если аргумент
limit
опущен или отсутствует, то печатаются все записи. - Необязательный аргумент
f
можно использовать для указания альтернативного кадра стека для запуска. - Необязательный аргумент
file
имеет то же значение, что и для функцииtraceback.print_tb()
.
traceback.format_exc(limit=None, chain=True)
:
Функция traceback.format_exc()
похожа на traceback.print_exc(limit)
но возвращает строку вместо печати или сохранения в файл.
Примеры использования вывода на печать исключений и трассировки стека:
Пример наглядно демонстрирует различные способы печати исключения и обратной трассировки:
# test.py import sys, traceback def lumberjack(): bright_side_of_death() def bright_side_of_death(): return tuple()[0] try: lumberjack() except IndexError: exc_type, exc_value, exc_traceback = sys.exc_info() print("*** print_tb:") traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) print("*** print_exception:") # exc_type below is ignored on 3.5 and later traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) print("*** print_exc:") traceback.print_exc(limit=2, file=sys.stdout) print("*** format_exc, first and last line:") formatted_lines = traceback.format_exc().splitlines() print(formatted_lines[0]) print(formatted_lines[-1])
Результаты вывода:
$ python3 test.py *** print_tb: File "<test...>", line 10, in <module> lumberjack() *** print_exception: Traceback (most recent call last): File "<test...>", line 10, in <module> lumberjack() File "<test...>", line 4, in lumberjack bright_side_of_death() IndexError: tuple index out of range *** print_exc: Traceback (most recent call last): File "<test...>", line 10, in <module> lumberjack() File "<test...>", line 4, in lumberjack bright_side_of_death() IndexError: tuple index out of range *** format_exc, first and last line: Traceback (most recent call last): IndexError: tuple index out of range ``
Purpose: | Extract, format, and print exceptions and stack traces. |
---|---|
Available In: | 1.4 and later, with modifications over time |
The traceback module works with the call stack to produce error
messages. A traceback is a stack trace from the point of an exception
handler down the call chain to the point where the exception was
raised. You can also work with the current call stack up from the
point of a call (and without the context of an error), which is useful
for finding out the paths being followed into a function.
The functions in traceback fall into several common categories.
There are functions for extracting raw tracebacks from the current
runtime environment (either an exception handler for a traceback, or
the regular stack). The extracted stack trace is a sequence of tuples
containing the filename, line number, function name, and text of the
source line.
Once extracted, the stack trace can be formatted using functions like
format_exception(), format_stack(), etc. The format
functions return a list of strings with messages formatted to be
printed. There are shorthand functions for printing the formatted
values, as well.
Although the functions in traceback mimic the behavior of the
interactive interpreter by default, they also are useful for handling
exceptions in situations where dumping the full stack trace to stderr
is not desirable. For example, a web application may need to format
the traceback so it looks good in HTML. An IDE may convert the
elements of the stack trace into a clickable list that lets the user
browse the source.
Supporting Functions¶
The examples below use the module traceback_example.py (provided in
the source package for PyMOTW). The contents are:
import traceback import sys def produce_exception(recursion_level=2): sys.stdout.flush() if recursion_level: produce_exception(recursion_level-1) else: raise RuntimeError() def call_function(f, recursion_level=2): if recursion_level: return call_function(f, recursion_level-1) else: return f()
Working With Exceptions¶
The simplest way to handle exception reporting is with
print_exc(). It uses sys.exc_info() to obtain the
exception information for the current thread, formats the results, and
prints the text to a file handle (sys.stderr, by default).
import traceback import sys from traceback_example import produce_exception print 'print_exc() with no exception:' traceback.print_exc(file=sys.stdout) print try: produce_exception() except Exception, err: print 'print_exc():' traceback.print_exc(file=sys.stdout) print print 'print_exc(1):' traceback.print_exc(limit=1, file=sys.stdout)
In this example, the file handle for sys.stdout is substituted so
the informational and traceback messages are mingled correctly:
$ python traceback_print_exc.py print_exc() with no exception: None print_exc(): Traceback (most recent call last): File "traceback_print_exc.py", line 20, in <module> produce_exception() File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exception produce_exception(recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exception produce_exception(recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 18, in produce_exception raise RuntimeError() RuntimeError print_exc(1): Traceback (most recent call last): File "traceback_print_exc.py", line 20, in <module> produce_exception() RuntimeError
print_exc() is just a shortcut for print_exception(),
which requires explicit arguments:
import traceback import sys from traceback_example import produce_exception try: produce_exception() except Exception, err: print 'print_exception():' exc_type, exc_value, exc_tb = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_tb)
$ python traceback_print_exception.py Traceback (most recent call last): File "traceback_print_exception.py", line 16, in <module> produce_exception() File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exception produce_exception(recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exception produce_exception(recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 18, in produce_exception raise RuntimeError() RuntimeError print_exception():
And print_exception() uses format_exception():
import traceback import sys from pprint import pprint from traceback_example import produce_exception try: produce_exception() except Exception, err: print 'format_exception():' exc_type, exc_value, exc_tb = sys.exc_info() pprint(traceback.format_exception(exc_type, exc_value, exc_tb))
$ python traceback_format_exception.py format_exception(): ['Traceback (most recent call last):n', ' File "traceback_format_exception.py", line 17, in <module>n produce_exception()n', ' File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exceptionn produce_exception(recursion_level-1)n', ' File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exceptionn produce_exception(recursion_level-1)n', ' File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 18, in produce_exceptionn raise RuntimeError()n', 'RuntimeErrorn']
Working With the Stack¶
There are a similar set of functions for performing the same operations with
the current call stack instead of a traceback.
print_stack()¶
import traceback import sys from traceback_example import call_function def f(): traceback.print_stack(file=sys.stdout) print 'Calling f() directly:' f() print print 'Calling f() from 3 levels deep:' call_function(f)
$ python traceback_print_stack.py Calling f() directly: File "traceback_print_stack.py", line 19, in <module> f() File "traceback_print_stack.py", line 16, in f traceback.print_stack(file=sys.stdout) Calling f() from 3 levels deep: File "traceback_print_stack.py", line 23, in <module> call_function(f) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 22, in call_function return call_function(f, recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 22, in call_function return call_function(f, recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 24, in call_function return f() File "traceback_print_stack.py", line 16, in f traceback.print_stack(file=sys.stdout)
format_stack()¶
import traceback import sys from pprint import pprint from traceback_example import call_function def f(): return traceback.format_stack() formatted_stack = call_function(f) pprint(formatted_stack)
$ python traceback_format_stack.py [' File "traceback_format_stack.py", line 19, in <module>n formatted_stack = call_function(f)n', ' File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 22, in call_functionn return call_function(f, recursion_level-1)n', ' File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 22, in call_functionn return call_function(f, recursion_level-1)n', ' File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 24, in call_functionn return f()n', ' File "traceback_format_stack.py", line 17, in fn return traceback.format_stack()n']
- HowTo
- Python How-To’s
- Print Stack Trace in Python
- Print Stack Trace in Python Using
traceback
Module - Print Stack Trace in Python Using the
logging.exception()
Method
In this tutorial, we will look into various methods to print the stack trace without stopping the execution of the program in Python.
A stack trace contains a list of active method calls at a specific time. We can print the stack trace in Python using the following methods.
Print Stack Trace in Python Using traceback
Module
The traceback
module provides the functionalities to extract, format, and print stack traces in Python. The traceback.format_exc()
method returns a string that contains the information about exception and stack trace entries from the traceback object.
We can use the format_exc()
method to print the stack trace with the try
and except
statements. The example code below demonstrates how to print the stack trace using the traceback.format_exc()
method in Python.
import traceback
import sys
try:
myfunction()
except Exception:
print(traceback.format_exc())
Output:
Traceback (most recent call last):
File "C:Testtest.py", line 5, in <module>
myfunction()
NameError: name 'myfunction' is not defined
Instead of using the print()
function, we can also use the logger.debug()
method to log the output, as logging can make debugging easier. We can log the stack trace in Python by using the logger.debug()
method in the following method.
import logging
import traceback
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
try:
myfunction()
except Exception:
logger.debug(traceback.format_exc())
Output:
DEBUG:__main__:Traceback (most recent call last):
File "C:Testtest.py", line 8, in <module>
myfunction()
NameError: name 'myfunction' is not defined
Print Stack Trace in Python Using the logging.exception()
Method
We can also use the logging.exception()
method of the logging
module to get the stack trace in Python. The logging.exception()
method logs the message containing the exception information. We can use it to print stack trace in Python in the following way.
import logging
import traceback
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
try:
myfunction()
except Exception:
logging.info('General exception noted.', exc_info=True)
Output:
INFO:root:General exception noted.
Traceback (most recent call last):
File "C:Testtest.py", line 8, in <module>
myfunction()
NameError: name 'myfunction' is not defined