bdb — Debugger framework

Вихідний код: Lib/bdb.py


Модуль bdb обробляє основні функції налагоджувача, як-от встановлення точок зупину або керування виконанням через налагоджувач.

Визначено такий виняток:

exception bdb.BdbQuit

Виняток, створений класом Bdb для виходу з налагоджувача.

Модуль bdb також визначає два класи:

class bdb.Breakpoint(self, file, line, temporary=0, cond=None, funcname=None)

Цей клас реалізує тимчасові точки зупинки, ігнорування підрахунків, відключення та (повторне) увімкнення, а також умови.

Точки зупину індексуються за номером у списку під назвою bpbynumber та парами (файл, рядок) через bplist. Перший вказує на єдиний екземпляр класу Breakpoint. Останній вказує на список таких випадків, оскільки на рядок може бути більше однієї точки зупину.

When creating a breakpoint, its associated filename should be in canonical form. If a funcname is defined, a breakpoint hit will be counted when the first line of that function is executed. A conditional breakpoint always counts a hit.

Екземпляри Breakpoint мають такі методи:

deleteMe()

Видалити точку зупину зі списку, пов’язаного з файлом/рядком. Якщо це остання точка зупину в цій позиції, вона також видаляє запис для файлу/рядка.

enable()

Позначте точку зупину як увімкнену.

disable()

Позначте точку зупину як вимкнену.

bpformat()

Повертає рядок з усією інформацією про точку зупину, красиво відформатований:

  • The breakpoint number.

  • If it is temporary or not.

  • Its file,line position.

  • The condition that causes a break.

  • If it must be ignored the next N times.

  • The breakpoint hit count.

Нове в версії 3.2.

bpprint(out=None)

Надрукувати вихідні дані bpformat() у файл out, або, якщо він None, у стандартний вихід.

class bdb.Bdb(skip=None)

Клас Bdb діє як загальний базовий клас налагоджувача Python.

Цей клас піклується про деталі засобу трасування; похідний клас повинен реалізовувати взаємодію з користувачем. Прикладом є стандартний клас відладчика (pdb.Pdb).

Аргумент skip, якщо він наданий, має бути повторюваним шаблоном імен модулів у стилі glob. Налагоджувач не ввійде в кадри, які походять із модуля, який відповідає одному з цих шаблонів. Чи вважається, що фрейм походить із певного модуля, визначається __name__ у глобальних параметрах фрейму.

Нове в версії 3.1: The skip argument.

Наступні методи Bdb зазвичай не потребують перевизначення.

canonic(filename)

Auxiliary method for getting a filename in a canonical form, that is, as a case-normalized (on case-insensitive filesystems) absolute path, stripped of surrounding angle brackets.

reset()

Set the botframe, stopframe, returnframe and quitting attributes with values ready to start debugging.

trace_dispatch(frame, event, arg)

Ця функція встановлена як функція трасування налагоджених кадрів. Його значенням, що повертається, є нова функція трасування (у більшості випадків, тобто сама).

Реалізація за замовчуванням вирішує, як відправляти кадр, залежно від типу події (переданої у вигляді рядка), яка має бути виконана. подією може бути одне з наступного:

  • "рядок": буде виконано новий рядок коду.

  • "виклик": функція буде викликана або введено інший блок коду.

  • "return": функція або інший блок коду збирається повернутися.

  • "exception": сталася виняток.

  • "c_call": функція C збирається викликатися.

  • "c_return": функція C повернулася.

  • "c_exception": функція C викликала виняток.

Для подій Python викликаються спеціалізовані функції (див. нижче). Для подій C не виконується жодних дій.

Параметр arg залежить від попередньої події.

Перегляньте документацію для sys.settrace(), щоб дізнатися більше про функцію трасування. Для отримання додаткової інформації про код і об’єкти фрейму зверніться до Стандартна ієрархія типів.

dispatch_line(frame)

If the debugger should stop on the current line, invoke the user_line() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_line()). Return a reference to the trace_dispatch() method for further tracing in that scope.

dispatch_call(frame, arg)

If the debugger should stop on this function call, invoke the user_call() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_call()). Return a reference to the trace_dispatch() method for further tracing in that scope.

dispatch_return(frame, arg)

If the debugger should stop on this function return, invoke the user_return() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_return()). Return a reference to the trace_dispatch() method for further tracing in that scope.

dispatch_exception(frame, arg)

If the debugger should stop at this exception, invokes the user_exception() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_exception()). Return a reference to the trace_dispatch() method for further tracing in that scope.

Зазвичай похідні класи не замінюють наступні методи, але вони можуть, якщо хочуть перевизначити визначення зупинки та точок зупинки.

stop_here(frame)

This method checks if the frame is somewhere below botframe in the call stack. botframe is the frame in which debugging started.

break_here(frame)

This method checks if there is a breakpoint in the filename and line belonging to frame or, at least, in the current function. If the breakpoint is a temporary one, this method deletes it.

break_anywhere(frame)

This method checks if there is a breakpoint in the filename of the current frame.

Похідні класи повинні перевизначати ці методи, щоб отримати контроль над роботою відладчика.

user_call(frame, argument_list)

This method is called from dispatch_call() when there is the possibility that a break might be necessary anywhere inside the called function.

user_line(frame)

This method is called from dispatch_line() when either stop_here() or break_here() yields True.

user_return(frame, return_value)

This method is called from dispatch_return() when stop_here() yields True.

user_exception(frame, exc_info)

This method is called from dispatch_exception() when stop_here() yields True.

do_clear(arg)

Визначте, як потрібно видалити точку зупину, якщо вона є тимчасовою.

Цей метод має бути реалізований похідними класами.

Похідні класи та клієнти можуть викликати наступні методи, щоб впливати на кроковий стан.

set_step()

Зупинка після одного рядка коду.

set_next(frame)

Зупиніться на наступному рядку в заданому кадрі або під ним.

set_return(frame)

Зупинка при поверненні із заданого кадру.

set_until(frame)

Stop when the line with the line no greater than the current one is reached or when returning from current frame.

set_trace([frame])

Почніть налагодження з фрейму. Якщо frame не вказано, налагодження починається з кадру абонента.

set_continue()

Зупиняйтеся лише в точках зупинки або після завершення. Якщо немає контрольних точок, встановіть для функції трасування системи значення None.

set_quit()

Set the quitting attribute to True. This raises BdbQuit in the next call to one of the dispatch_*() methods.

Похідні класи та клієнти можуть викликати наведені нижче методи для керування точками зупинки. Ці методи повертають рядок, що містить повідомлення про помилку, якщо щось пішло не так, або None, якщо все добре.

set_break(filename, lineno, temporary=0, cond, funcname)

Встановіть нову точку зупинки. Якщо рядок lineno не існує для ім’я файлу, переданого як аргумент, поверніть повідомлення про помилку. Ім’я файлу має бути в канонічній формі, як описано в методі canonic().

clear_break(filename, lineno)

Delete the breakpoints in filename and lineno. If none were set, an error message is returned.

clear_bpbynumber(arg)

Видаліть точку зупину, яка має індекс arg у Breakpoint.bpbynumber. Якщо arg не є числом або виходить за межі діапазону, повертає повідомлення про помилку.

clear_all_file_breaks(filename)

Delete all breakpoints in filename. If none were set, an error message is returned.

clear_all_breaks()

Delete all existing breakpoints.

get_bpbynumber(arg)

Повертає точку зупину, визначену заданим числом. Якщо arg є рядком, його буде перетворено на число. Якщо arg є нечисловим рядком, якщо задана точка зупину ніколи не існувала або була видалена, виникає ValueError.

Нове в версії 3.2.

get_break(filename, lineno)

Check if there is a breakpoint for lineno of filename.

get_breaks(filename, lineno)

Повертає всі контрольні точки для lineno в імені файлу або порожній список, якщо жодна з них не встановлена.

get_file_breaks(filename)

Повертає всі контрольні точки в назві файлу або порожній список, якщо жодна з них не встановлена.

get_all_breaks()

Повернути всі встановлені точки зупину.

Похідні класи та клієнти можуть викликати наведені нижче методи, щоб отримати структуру даних, що представляє трасування стека.

get_stack(f, t)

Get a list of records for a frame and all higher (calling) and lower frames, and the size of the higher part.

format_stack_entry(frame_lineno, lprefix=': ')

Return a string with information about a stack entry, identified by a (frame, lineno) tuple:

  • The canonical form of the filename which contains the frame.

  • The function name, or "<lambda>".

  • Вхідні аргументи.

  • Повернене значення.

  • Рядок коду (якщо він існує).

Наступні два методи можуть бути викликані клієнтами для використання налагоджувача для налагодження statement, поданого як рядок.

run(cmd, globals=None, locals=None)

Debug a statement executed via the exec() function. globals defaults to __main__.__dict__, locals defaults to globals.

runeval(expr, globals=None, locals=None)

Налагодити вираз, що виконується за допомогою функції eval(). globals і locals мають те саме значення, що й у run().

runctx(cmd, globals, locals)

Для зворотної сумісності. Викликає метод run().

runcall(func, *args, **kwds)

Налагодити один виклик функції та повернути його результат.

Нарешті, модуль визначає такі функції:

bdb.checkfuncname(b, frame)

Check whether we should break here, depending on the way the breakpoint b was set.

If it was set via line number, it checks if b.line is the same as the one in the frame also passed as argument. If the breakpoint was set via function name, we have to check we are in the right frame (the right function) and if we are in its first executable line.

bdb.effective(file, line, frame)

Determine if there is an effective (active) breakpoint at this line of code. Return a tuple of the breakpoint and a boolean that indicates if it is ok to delete a temporary breakpoint. Return (None, None) if there is no matching breakpoint.

bdb.set_trace()

Почніть налагодження з екземпляра Bdb із фрейму абонента.