bdb — Debugger framework¶
Вихідний код: Lib/bdb.py
Модуль bdb обробляє основні функції налагоджувача, як-от встановлення точок зупину або керування виконанням через налагоджувач.
Визначено такий виняток:
Модуль bdb також визначає два класи:
- class bdb.Breakpoint(self, file, line, temporary=False, cond=None, funcname=None)¶
Цей клас реалізує тимчасові точки зупинки, ігнорування підрахунків, відключення та (повторне) увімкнення, а також умови.
Точки зупину індексуються за номером у списку під назвою
bpbynumberта парами(файл, рядок)черезbplist. Перший вказує на єдиний екземпляр класуBreakpoint. Останній вказує на список таких випадків, оскільки на рядок може бути більше однієї точки зупину.When creating a breakpoint, its associated
file nameshould be in canonical form. If afuncnameis defined, a breakpointhitwill be counted when the first line of that function is executed. Aconditionalbreakpoint always counts ahit.Екземпляри
Breakpointмають такі методи:- deleteMe()¶
Видалити точку зупину зі списку, пов’язаного з файлом/рядком. Якщо це остання точка зупину в цій позиції, вона також видаляє запис для файлу/рядка.
- enable()¶
Позначте точку зупину як увімкнену.
- disable()¶
Позначте точку зупину як вимкнену.
- bpformat()¶
Повертає рядок з усією інформацією про точку зупину, красиво відформатований:
Breakpoint number.
Temporary status (del or keep).
File/line position.
Break condition.
Number of times to ignore.
Number of times hit.
Added in version 3.2.
- bpprint(out=None)¶
Надрукувати вихідні дані
bpformat()у файл out, або, якщо вінNone, у стандартний вихід.
Breakpointinstances have the following attributes:- file¶
File name of the
Breakpoint.
- line¶
Line number of the
Breakpointwithinfile.
- temporary¶
Trueif aBreakpointat (file, line) is temporary.
- cond¶
Condition for evaluating a
Breakpointat (file, line).
- funcname¶
Function name that defines whether a
Breakpointis hit upon entering the function.
- enabled¶
TrueifBreakpointis enabled.
- bpbynumber¶
Numeric index for a single instance of a
Breakpoint.
- bplist¶
Dictionary of
Breakpointinstances indexed by (file,line) tuples.
- ignore¶
Number of times to ignore a
Breakpoint.
- hits¶
Count of the number of times a
Breakpointhas been hit.
- class bdb.Bdb(skip=None)¶
Клас
Bdbдіє як загальний базовий клас налагоджувача Python.Цей клас піклується про деталі засобу трасування; похідний клас повинен реалізовувати взаємодію з користувачем. Прикладом є стандартний клас відладчика (
pdb.Pdb).Аргумент skip, якщо він наданий, має бути повторюваним шаблоном імен модулів у стилі glob. Налагоджувач не ввійде в кадри, які походять із модуля, який відповідає одному з цих шаблонів. Чи вважається, що фрейм походить із певного модуля, визначається
__name__у глобальних параметрах фрейму.Змінено в версії 3.1: Added the skip parameter.
Наступні методи
Bdbзазвичай не потребують перевизначення.- canonic(filename)¶
Return canonical form of filename.
For real file names, the canonical form is an operating-system-dependent,
case-normalizedabsolute path. A filename with angle brackets, such as"<stdin>"generated in interactive mode, is returned unchanged.
- reset()¶
Set the
botframe,stopframe,returnframeandquittingattributes 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 aBdbQuitexception if thequittingflag is set (which can be set fromuser_line()). Return a reference to thetrace_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 aBdbQuitexception if thequittingflag is set (which can be set fromuser_call()). Return a reference to thetrace_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 aBdbQuitexception if thequittingflag is set (which can be set fromuser_return()). Return a reference to thetrace_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 aBdbQuitexception if thequittingflag is set (which can be set fromuser_exception()). Return a reference to thetrace_dispatch()method for further tracing in that scope.
Зазвичай похідні класи не замінюють наступні методи, але вони можуть, якщо хочуть перевизначити визначення зупинки та точок зупинки.
- is_skipped_line(module_name)¶
Return
Trueif module_name matches any skip pattern.
- stop_here(frame)¶
Return
Trueif frame is below the starting frame in the stack.
- break_here(frame)¶
Return
Trueif there is an effective breakpoint for this line.Check whether a line or function breakpoint exists and is in effect. Delete temporary breakpoints based on information from
effective().
- break_anywhere(frame)¶
Return
Trueif any breakpoint exists for frame’s filename.
Похідні класи повинні перевизначати ці методи, щоб отримати контроль над роботою відладчика.
- user_call(frame, argument_list)¶
Called from
dispatch_call()if a break might stop inside the called function.argument_list is not used anymore and will always be
None. The argument is kept for backwards compatibility.
- user_line(frame)¶
Called from
dispatch_line()when eitherstop_here()orbreak_here()returnsTrue.
- user_return(frame, return_value)¶
Called from
dispatch_return()whenstop_here()returnsTrue.
- user_exception(frame, exc_info)¶
Called from
dispatch_exception()whenstop_here()returnsTrue.
- do_clear(arg)¶
Визначте, як потрібно видалити точку зупину, якщо вона є тимчасовою.
Цей метод має бути реалізований похідними класами.
Похідні класи та клієнти можуть викликати наступні методи, щоб впливати на кроковий стан.
- set_step()¶
Зупинка після одного рядка коду.
- set_next(frame)¶
Зупиніться на наступному рядку в заданому кадрі або під ним.
- set_return(frame)¶
Зупинка при поверненні із заданого кадру.
- set_until(frame, lineno=None)¶
Stop when the line with the lineno greater than the current one is reached or when returning from current frame.
- set_trace([frame])¶
Почніть налагодження з фрейму. Якщо frame не вказано, налагодження починається з кадру абонента.
Змінено в версії 3.13:
set_trace()will enter the debugger immediately, rather than on the next line of code to be executed.
- set_continue()¶
Зупиняйтеся лише в точках зупинки або після завершення. Якщо немає контрольних точок, встановіть для функції трасування системи значення
None.
- set_quit()¶
Set the
quittingattribute toTrue. This raisesBdbQuitin the next call to one of thedispatch_*()methods.
Похідні класи та клієнти можуть викликати наведені нижче методи для керування точками зупинки. Ці методи повертають рядок, що містить повідомлення про помилку, якщо щось пішло не так, або
None, якщо все добре.- set_break(filename, lineno, temporary=False, cond=None, funcname=None)¶
Встановіть нову точку зупинки. Якщо рядок lineno не існує для ім’я файлу, переданого як аргумент, поверніть повідомлення про помилку. Ім’я файлу має бути в канонічній формі, як описано в методі
canonic().
- clear_break(filename, lineno)¶
Delete the breakpoints in filename and lineno. If none were set, return an error message.
- clear_bpbynumber(arg)¶
Видаліть точку зупину, яка має індекс arg у
Breakpoint.bpbynumber. Якщо arg не є числом або виходить за межі діапазону, повертає повідомлення про помилку.
- clear_all_file_breaks(filename)¶
Delete all breakpoints in filename. If none were set, return an error message.
- clear_all_breaks()¶
Delete all existing breakpoints. If none were set, return an error message.
- get_bpbynumber(arg)¶
Повертає точку зупину, визначену заданим числом. Якщо arg є рядком, його буде перетворено на число. Якщо arg є нечисловим рядком, якщо задана точка зупину ніколи не існувала або була видалена, виникає
ValueError.Added in version 3.2.
- get_break(filename, lineno)¶
Return
Trueif there is a breakpoint for lineno in filename.
- get_breaks(filename, lineno)¶
Повертає всі контрольні точки для lineno в імені файлу або порожній список, якщо жодна з них не встановлена.
- get_file_breaks(filename)¶
Повертає всі контрольні точки в назві файлу або порожній список, якщо жодна з них не встановлена.
- get_all_breaks()¶
Повернути всі встановлені точки зупину.
Похідні класи та клієнти можуть викликати наведені нижче методи, щоб отримати структуру даних, що представляє трасування стека.
- get_stack(f, t)¶
Return a list of (frame, lineno) tuples in a stack trace, and a size.
The most recently called frame is last in the list. The size is the number of frames below the frame where the debugger was invoked.
- format_stack_entry(frame_lineno, lprefix=': ')¶
Return a string with information about a stack entry, which is a
(frame, lineno)tuple. The return string contains:The canonical 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().
- runcall(func, /, *args, **kwds)¶
Налагодити один виклик функції та повернути його результат.
Нарешті, модуль визначає такі функції:
- bdb.checkfuncname(b, frame)¶
Return
Trueif we should break here, depending on the way theBreakpointb was set.If it was set via line number, it checks if
b.lineis the same as the one in frame. If the breakpoint was set viafunction name, we have to check we are in the right frame (the right function) and if we are on its first executable line.
- bdb.effective(file, line, frame)¶
Return
(active breakpoint, delete temporary flag)or(None, None)as the breakpoint to act upon.The active breakpoint is the first entry in
bplistfor the (file,line) (which must exist) that isenabled, for whichcheckfuncname()is true, and that has neither a falseconditionnor positiveignorecount. The flag, meaning that a temporary breakpoint should be deleted, isFalseonly when thecondcannot be evaluated (in which case,ignorecount is ignored).If no such entry exists, then
(None, None)is returned.