Модуль traceback в Python, трассировки стека
Модуль traceback предоставляет стандартный интерфейс для извлечения, форматирования и вывода на печать трассировок стека программ Python. Модуль точно имитирует поведение интерпретатора Python при печати трассировки стека.
Модуль traceback полезен, когда появляется необходимость распечатать трассировку стека под управлением программы.
Модуль использует объекты трассировки — это тип объекта, который сохраняется в переменной sys.last_traceback и возвращается как третий элемент из sys.exc_info() .
Примеры использования модуля traceback :
Этот простой пример реализует базовый цикл read-eval-print , аналогичный стандартному интерактивному интерпретатору Python. Для более полной реализации эмуляции интерпретатора смотрите описание модуля code .
# test.py import sys, traceback def run_user_code(envdir): source = input(">>> ") try: exec(source, envdir) except Exception: print("Exception in user code:") print("-"*60) traceback.print_exc(file=sys.stdout) print("-"*60) envdir = <> while True: run_user_code(envdir)
Запускаем эмуляцию интерпретатора Python.
$ python3 test.py >>> a = 3 >>> b = '1' >>> a + b Exception in user code: ------------------------------------------------------------ Traceback (most recent call last): File "tt.py", line 6, in run_user_code exec(source, envdir) File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'str' ------------------------------------------------------------
В следующем примере показаны различные способы печати и форматирования стека:
>>> import traceback >>> def another_function(): . lumberstack() . >>> def lumberstack(): . traceback.print_stack() . print(repr(traceback.extract_stack())) . print(repr(traceback.format_stack())) . >>> another_function() # File "", line 1, in # File "", line 2, in another_function # File "", line 2, in lumberstack # [, #, #] # [' File "", line 1, in \n', ' File "", # line 2, in another_function\n', ' File "", # line 4, in lumberstack\n']
- КРАТКИЙ ОБЗОР МАТЕРИАЛА.
- Вывод трассировки на печать или в файл, модуль traceback
- Извлечение записей трассировки стека, модуль traceback
- Форматирование трассировок и исключений модулем traceback
Вывод трассировки на печать или в файл, модуль traceback в Python
Печать или вывод в файл информации об исключениях и записей трассировки стека
Содержание:
- 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 в файл.
- Если 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 "", line 10, in lumberjack() *** print_exception: Traceback (most recent call last): File "", line 10, in lumberjack() File "", line 4, in lumberjack bright_side_of_death() IndexError: tuple index out of range *** print_exc: Traceback (most recent call last): File "", line 10, in lumberjack() File "", 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 ``
- КРАТКИЙ ОБЗОР МАТЕРИАЛА.
- Вывод трассировки на печать или в файл, модуль traceback
- Извлечение записей трассировки стека, модуль traceback
- Форматирование трассировок и исключений модулем traceback
Повторение материала. Работа с ошибками в Python.
Наш код подразумевает печать содержимого переменной vector.
Запустим написанный скрипт, получим следующий вывод:
$ python3 solution.py Traceback (most recent call last): File "solution.py", line 1, in for coord in vector: NameError: name 'vector' is not defined
Сообщение означает, что при исполнении кода возникла ошибка. При этом Python сообщает нам кое-что ещё. Разберём это сообщение детально.
Чтение Traceback 1
Исходное сообщение нужно мысленно разделить на две части. Первая часть это traceback-сообщение:
Traceback (most recent call last): File "solution.py", line 1, in for coord in vector:
Вторая часть — сообщение о возникшей ошибке:
NameError: name 'vector' is not defined
Разберём первую часть. Traceback в грубом переводе означает «отследить назад». Traceback показывает последовательность/стэк вызовов, которая, в конечном итоге, вызвала ошибку.
Traceback (most recent call last):
является заголовочной. Она сообщает, что в последующих строках будет изложен стэк вызовов (он показан отступами). Обратите внимание на сообщение в скобках, оно указывает на порядок вызовов. В данном случае (он же случай по умолчанию) тот вызов, в котором произошла ошибка, будет в последовательности вызовов указан последним.
Вторая и третья строки:
File "solution.py", line 1, in for coord in vector:
показывают информацию о вызове (в нашем случае он один). Во-первых, здесь есть информация о файле, в котором произошёл вызов («solution.py»), затем указан номер строки, где этот вызов происходит («line 1»), в конце стоит информация о том, откуда произошёл вызов («»). В нашем случае вызов происходит непосредственно из модуля, т.е. не из функции. Наконец, вывод содержит не только номер строки, но и саму строку «for coord in vector:».
Заключительная строка сообщения:
NameError: name 'vector' is not defined
содержит вид (тип) ошибки («NameError»), и после двоеточия содержит подсказку. В данном случае она означает, что имя «vector» не определено.
В самом деле, если взглянуть снова на код, то можно убедиться, что мы нигде не объявили переменную «vector».
Подведём итоги. При попытке запуска мы получили следующий вывод
$ python3 solution.py Traceback (most recent call last): File "solution.py", line 1, in for coord in vector: NameError: name 'vector' is not defined
Он говорит нам о возникновении ошибки. Эта ошибка обнаружилась интерпретатором в первой строке файла «solution.py». Сама ошибка является ошибкой имени и указывает на необъявленное имя — «vector».
Чтение Traceback 2
Оберните код из solution.py в функцию:
1 2 3 4 5
def print_vector(vector): for coord in vector: print(coord) print_vector(5)
Запустим наш код
$ python3 solution.py Traceback (most recent call last): File "solution.py", line 5, in print_vector(5) File "solution.py", line 2, in print_vector for coord in vector: TypeError: 'int' object is not iterable
На этот раз сообщение об ошибке сложнее, однако структура у него та же.
Часть со стеком вызовов увеличилась:
Traceback (most recent call last): File "solution.py", line 5, in print_vector(5) File "solution.py", line 2, in print_vector for coord in vector:
Поскольку «most recent call last», читать будем её сверху вниз.
Вызовов на этот раз два. Первый вызов:
File "solution.py", line 5, in print_vector(5)
Произошел в пятой строке. Судя по строчке кода, это вызов написанной нами функции print_vector(5) с аргументом 5.
Следом за ней второй вызов:
File "solution.py", line 2, in print_vector for coord in vector:
Этот вызов происходит внутри функции print_vector, содержащейся в файле «solution.py». Вызов находится в строке 2.
Сама же ошибка имеет вид:
TypeError: 'int' object is not iterable
Как и в первом примере, сообщение об ошибке содержит её тип и подсказку. В нашем случае произошла ошибка типа. В подсказке же указано, что объект типа int не является итерируемым, т.е. таким объектом, который нельзя использовать в цикле for.
$ python3 solution.py Traceback (most recent call last): File "solution.py", line 5, in print_vector(5) File "solution.py", line 2, in print_vector for coord in vector: TypeError: 'int' object is not iterable
В нашем коде возникла ошибка. Её вызвала последовательность вызовов. Первый вызов произошел непосредственно из модуля — в строке 5 происходит вызов функции print_vector(5). Внутри этой функции ошибка возникла в строчке 2, содержащей проход по циклу. Сообщение об ошибке означает, что итерироваться по объекту типа int нельзя. В нашем случае мы вызвали функцию print_vector от числа (от 5).
Некоторые ошибки с примерами кода
Ошибки в синтаксисе
Наиболее частая ошибка, которая возникает в программах на Python — SyntaxError: когда какое-то утверждение записано не по правилам языка, например:
$ python3 >>> print "hello" File "", line 1 print "hello" ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello")?
Тот же тип ошибки возникнет, если забыть поставить двоеточие в цикле:
$ python3 >>> for i in range(5) File "", line 1 for i in range(5) ^ SyntaxError: invalid syntax
При неправильном использовании пробелов и табуляций в начале строки возникает IndentationError:
$ python3 >>> for i in range(5): print(i) File "", line 2 print(i) ^ IndentationError: expected an indented block
А теперь посмотрим, что будет, если в первой строке цикла воспользоваться пробелами, а во второй — табуляцией:
$ python3 >>> for i in range(5): print(i) # здесь пробелы print(i**2) # здесь табуляция File "", line 3 print(i**2) ^ TabError: inconsistent use of tabs and spaces in indentation
NameError возникает при обращении к несуществующей переменной:
$ python3 >>> words = "Hello" >>> word Traceback (most recent call last): File "", line 1, in NameError: name 'word' is not defined
Ошибки в логике
Напишем простую программу на деление с остатком и сохраним как sample.py:
n = input() m = input() print(n % m)
$ python3 sample.py 5 3 Traceback (most recent call last): File "sample.py", line 3, in print(n % m) TypeError: not all arguments converted during string formatting
Возникла ошибка TypeError, которая сообщает о неподходящем типе данных. Исправим программу:
n = int(input()) m = int(input()) print(n % m)
запустим на неподходящих данных:
$ python3 sample.py xyz Traceback (most recent call last): File "sample.py", line 1, in n = int(input()) ValueError: invalid literal for int() with base 10: 'xyz'
Возникнет ValueError. Эту ошибку ещё можно воспринимать как использование значения вне области допустимых значений (ОДЗ).
Теперь запустим программу на числовых данных:
$ python3 sample.py 1 0 Traceback (most recent call last): File "sample.py", line 3, in print(n % m) ZeroDivisionError: integer division or modulo by zero
При работе с массивами нередко возникает ошибка IndexError. Она возникает при выходе за пределы массива:
$ python3 >>> L1 = [1, 2, 3] >>> L1[3] Traceback (most recent call last): File "", line 1, in IndexError: list index out of range
Что будет, если вызвать бесконечную рекурсию? Опишем её в программе endless.py
def noend(): print("Hello!") noend() noend()
Через некоторое время после запуска возникнет RecursionError:
Traceback (most recent call last): File "endless.py", line 4, in noend() File "endless.py", line 3, in noend noend() File "endless.py", line 3, in noend noend() File "endless.py", line 3, in noend noend() [Previous line repeated 993 more times] File "endless.py", line 2, in noend print("Hello!") RecursionError: maximum recursion depth exceeded while calling a Python object
Контест №1
Сайт построен с использованием Pelican. За основу оформления взята тема от Smashing Magazine. Исходные тексты программ, приведённые на этом сайте, распространяются под лицензией GPLv3, все остальные материалы сайта распространяются под лицензией CC-BY.
29.9. traceback — Print or retrieve a stack traceback¶
This module provides a standard interface to extract, format and print stack traces of Python programs. It exactly mimics the behavior of the Python interpreter when it prints a stack trace. This is useful when you want to print stack traces under program control, such as in a « wrapper » around the interpreter.
The module uses traceback objects — this is the object type that is stored in the sys.last_traceback variable and returned as the third item from sys.exc_info() .
Le module définit les fonctions suivantes :
traceback. print_tb ( tb, limit=None, file=None ) ¶
Print up to limit stack trace entries from traceback object tb (starting from the caller’s frame) if limit is positive. Otherwise, print the last abs(limit) entries. If limit is omitted or None , all entries are printed. If file is omitted or None , the output goes to sys.stderr ; otherwise it should be an open file or file-like object to receive the output.
Modifié dans la version 3.5: Added negative limit support.
traceback. print_exception ( etype, value, tb, limit=None, file=None, chain=True ) ¶
Print exception information and stack trace entries from traceback object tb to file. 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 etype and value after the stack trace
- if type(value) 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.
The optional limit argument has the same meaning as for print_tb() . If chain is true (the default), then chained exceptions (the __cause__ or __context__ attributes of the exception) will be printed as well, like the interpreter itself does when printing an unhandled exception.
Modifié dans la version 3.5: The etype argument is ignored and inferred from the type of value.
traceback. print_exc ( limit=None, file=None, chain=True ) ¶
This is a shorthand for print_exception(*sys.exc_info(), limit, file, chain) .
traceback. print_last ( limit=None, file=None, chain=True ) ¶
This is a shorthand for print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain) . In general it will work only after an exception has reached an interactive prompt (see sys.last_type ).
traceback. print_stack ( f=None, limit=None, file=None ) ¶
Print up to limit stack trace entries (starting from the invocation point) if limit is positive. Otherwise, print the last abs(limit) entries. If limit is omitted or None , all entries are printed. The optional f argument can be used to specify an alternate stack frame to start. The optional file argument has the same meaning as for print_tb() .
Modifié dans la version 3.5: Added negative limit support.
traceback. extract_tb ( tb, limit=None ) ¶
Return a StackSummary object representing a list of « pre-processed » stack trace entries extracted from the traceback object tb. It is useful for alternate formatting of stack traces. The optional limit argument has the same meaning as for print_tb() . A « pre-processed » stack trace entry is a FrameSummary object containing attributes filename , lineno , name , and line representing the information that is usually printed for a stack trace. The line is a string with leading and trailing whitespace stripped; if the source is not available it is None .
traceback. extract_stack ( f=None, limit=None ) ¶
Extract the raw traceback from the current stack frame. The return value has the same format as for extract_tb() . The optional f and limit arguments have the same meaning as for print_stack() .
traceback. format_list ( extracted_list ) ¶
Given a list of tuples or FrameSummary objects as returned by extract_tb() or extract_stack() , return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None .
traceback. format_exception_only ( etype, value ) ¶
Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value . The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list.
traceback. format_exception ( etype, value, tb, limit=None, chain=True ) ¶
Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to print_exception() . The return value is a list of strings, each ending in a newline and some containing internal newlines. When these lines are concatenated and printed, exactly the same text is printed as does print_exception() .
Modifié dans la version 3.5: The etype argument is ignored and inferred from the type of value.
traceback. format_exc ( limit=None, chain=True ) ¶
This is like print_exc(limit) but returns a string instead of printing to a file.
traceback. format_tb ( tb, limit=None ) ¶
A shorthand for format_list(extract_tb(tb, limit)) .
traceback. format_stack ( f=None, limit=None ) ¶
A shorthand for format_list(extract_stack(f, limit)) .
traceback. clear_frames ( tb ) ¶
Clears the local variables of all the stack frames in a traceback tb by calling the clear() method of each frame object.
Nouveau dans la version 3.4.
traceback. walk_stack ( f ) ¶
Walk a stack following f.f_back from the given frame, yielding the frame and line number for each frame. If f is None , the current stack is used. This helper is used with StackSummary.extract() .
Nouveau dans la version 3.5.
traceback. walk_tb ( tb ) ¶
Walk a traceback following tb_next yielding the frame and line number for each frame. This helper is used with StackSummary.extract() .
Nouveau dans la version 3.5.
The module also defines the following classes:
29.9.1. TracebackException Objects¶
Nouveau dans la version 3.5.
TracebackException objects are created from actual exceptions to capture data for later printing in a lightweight fashion.
class traceback. TracebackException ( exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False ) ¶
Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class.
Note that when locals are captured, they are also shown in the traceback.
A TracebackException of the original __cause__ .
A TracebackException of the original __context__ .
The __suppress_context__ value from the original exception.
A StackSummary representing the traceback.
The class of the original traceback.
For syntax errors — the file name where the error occurred.
For syntax errors — the line number where the error occurred.
For syntax errors — the text where the error occurred.
For syntax errors — the offset into the text where the error occurred.
For syntax errors — the compiler error message.
classmethod from_exception ( exc, *, limit=None, lookup_lines=True, capture_locals=False ) ¶
Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class.
Note that when locals are captured, they are also shown in the traceback.
Format the exception.
If chain is not True , __cause__ and __context__ will not be formatted.
The return value is a generator of strings, each ending in a newline and some containing internal newlines. print_exception() is a wrapper around this method which just prints the lines to a file.
The message indicating which exception occurred is always the last string in the output.
Format the exception part of the traceback.
The return value is a generator of strings, each ending in a newline.
Normally, the generator emits a single string; however, for SyntaxError exceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred.
The message indicating which exception occurred is always the last string in the output.
29.9.2. StackSummary Objects¶
Nouveau dans la version 3.5.
StackSummary objects represent a call stack ready for formatting.
class traceback. StackSummary ¶ classmethod extract ( frame_gen, *, limit=None, lookup_lines=True, capture_locals=False ) ¶
Construct a StackSummary object from a frame generator (such as is returned by walk_stack() or walk_tb() ).
If limit is supplied, only this many frames are taken from frame_gen. If lookup_lines is False , the returned FrameSummary objects will not have read their lines in yet, making the cost of creating the StackSummary cheaper (which may be valuable if it may not actually get formatted). If capture_locals is True the local variables in each FrameSummary are captured as object representations.
classmethod from_list ( a_list ) ¶
Construct a StackSummary object from a supplied list of FrameSummary objects or old-style list of tuples. Each tuple should be a 4-tuple with filename, lineno, name, line as the elements.
Returns a list of strings ready for printing. Each string in the resulting list corresponds to a single frame from the stack. Each string ends in a newline; the strings may contain internal newlines as well, for those items with source text lines.
For long sequences of the same frame and line, the first few repetitions are shown, followed by a summary line stating the exact number of further repetitions.
Modifié dans la version 3.6: Long sequences of repeated frames are now abbreviated.
29.9.3. FrameSummary Objects¶
Nouveau dans la version 3.5.
FrameSummary objects represent a single frame in a traceback.
class traceback. FrameSummary ( filename, lineno, name, lookup_line=True, locals=None, line=None ) ¶
Represent a single frame in the traceback or stack that is being formatted or printed. It may optionally have a stringified version of the frames locals included in it. If lookup_line is False , the source code is not looked up until the FrameSummary has the line attribute accessed (which also happens when casting it to a tuple). line may be directly provided, and will prevent line lookups happening at all. locals is an optional local variable dictionary, and if supplied the variable representations are stored in the summary for later display.
29.9.4. Traceback Examples¶
This simple example implements a basic read-eval-print loop, similar to (but less useful than) the standard Python interactive interpreter loop. For a more complete implementation of the interpreter loop, refer to the code module.
import sys, traceback def run_user_code(envdir): source = input(">>> ") try: exec(source, envdir) except Exception: print("Exception in user code:") print("-"*60) traceback.print_exc(file=sys.stdout) print("-"*60) envdir = <> while True: run_user_code(envdir)
The following example demonstrates the different ways to print and format the exception and traceback:
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]) print("*** format_exception:") # exc_type below is ignored on 3.5 and later print(repr(traceback.format_exception(exc_type, exc_value, exc_traceback))) print("*** extract_tb:") print(repr(traceback.extract_tb(exc_traceback))) print("*** format_tb:") print(repr(traceback.format_tb(exc_traceback))) print("*** tb_lineno:", exc_traceback.tb_lineno)
The output for the example would look similar to this:
*** print_tb: File "", line 10, in lumberjack() *** print_exception: Traceback (most recent call last): File "", line 10, in lumberjack() File "", line 4, in lumberjack bright_side_of_death() IndexError: tuple index out of range *** print_exc: Traceback (most recent call last): File "", line 10, in lumberjack() File "", 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 *** format_exception: ['Traceback (most recent call last):\n', ' File "", line 10, in \n lumberjack()\n', ' File "", line 4, in lumberjack\n bright_side_of_death()\n', ' File "", line 7, in bright_side_of_death\n return tuple()[0]\n', 'IndexError: tuple index out of range\n'] *** extract_tb: [, , ] *** format_tb: [' File "", line 10, in \n lumberjack()\n', ' File "", line 4, in lumberjack\n bright_side_of_death()\n', ' File "", line 7, in bright_side_of_death\n return tuple()[0]\n'] *** tb_lineno: 10
The following example shows the different ways to print and format the stack:
>>> import traceback >>> def another_function(): . lumberstack() . >>> def lumberstack(): . traceback.print_stack() . print(repr(traceback.extract_stack())) . print(repr(traceback.format_stack())) . >>> another_function() File "", line 10, in another_function() File "", line 3, in another_function lumberstack() File "", line 6, in lumberstack traceback.print_stack() [('', 10, '', 'another_function()'), ('', 3, 'another_function', 'lumberstack()'), ('', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')] [' File "", line 10, in \n another_function()\n', ' File "", line 3, in another_function\n lumberstack()\n', ' File "", line 8, in lumberstack\n print(repr(traceback.format_stack()))\n']
This last example demonstrates the final few formatting functions:
>>> import traceback >>> traceback.format_list([('spam.py', 3, '', 'spam.eggs()'), . ('eggs.py', 42, 'eggs', 'return "bacon"')]) [' File "spam.py", line 3, in \n spam.eggs()\n', ' File "eggs.py", line 42, in eggs\n return "bacon"\n'] >>> an_error = IndexError('tuple index out of range') >>> traceback.format_exception_only(type(an_error), an_error) ['IndexError: tuple index out of range\n']