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 name
should be in canonical form. If afuncname
is defined, a breakpointhit
will be counted when the first line of that function is executed. Aconditional
breakpoint 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.
Нове в версії 3.2.
-
bpprint
(out=None)¶ Надрукувати вихідні дані
bpformat()
у файл out, або, якщо вінNone
, у стандартний вихід.
Breakpoint
instances have the following attributes:-
file
¶ File name of the
Breakpoint
.
-
line
¶ Line number of the
Breakpoint
withinfile
.
-
temporary
¶ True if a
Breakpoint
at (file, line) is temporary.
-
cond
¶ Condition for evaluating a
Breakpoint
at (file, line).
-
funcname
¶ Function name that defines whether a
Breakpoint
is hit upon entering the function.
-
enabled
¶ True if
Breakpoint
is enabled.
-
bpbynumber
¶ Numeric index for a single instance of a
Breakpoint
.
-
bplist
¶ Dictionary of
Breakpoint
instances indexed by (file
,line
) tuples.
-
ignore
¶ Number of times to ignore a
Breakpoint
.
-
hits
¶ Count of the number of times a
Breakpoint
has been hit.
-
-
class
bdb.
Bdb
(skip=None)¶ Клас
Bdb
діє як загальний базовий клас налагоджувача Python.Цей клас піклується про деталі засобу трасування; похідний клас повинен реалізовувати взаємодію з користувачем. Прикладом є стандартний клас відладчика (
pdb.Pdb
).Аргумент skip, якщо він наданий, має бути повторюваним шаблоном імен модулів у стилі glob. Налагоджувач не ввійде в кадри, які походять із модуля, який відповідає одному з цих шаблонів. Чи вважається, що фрейм походить із певного модуля, визначається
__name__
у глобальних параметрах фрейму.Нове в версії 3.1: The skip argument.
Наступні методи
Bdb
зазвичай не потребують перевизначення.-
canonic
(filename)¶ Return canonical form of filename.
For real file names, the canonical form is an operating-system-dependent,
case-normalized
absolute path
. A filename with angle brackets, such as"<stdin>"
generated in interactive mode, is returned unchanged.
-
reset
()¶ Set the
botframe
,stopframe
,returnframe
andquitting
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 aBdbQuit
exception if theBdb.quitting
flag 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 aBdbQuit
exception if theBdb.quitting
flag 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 aBdbQuit
exception if theBdb.quitting
flag 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 aBdbQuit
exception if theBdb.quitting
flag 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 True if module_name matches any skip pattern.
-
stop_here
(frame)¶ Return True if frame is below the starting frame in the stack.
-
break_here
(frame)¶ Return True if 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 True if 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.
-
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 не вказано, налагодження починається з кадру абонента.
-
set_continue
()¶ Зупиняйтеся лише в точках зупинки або після завершення. Якщо немає контрольних точок, встановіть для функції трасування системи значення
None
.
-
set_quit
()¶ Set the
quitting
attribute toTrue
. This raisesBdbQuit
in 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
.Нове в версії 3.2.
-
get_break
(filename, lineno)¶ Return True if 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 True if 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 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
bplist
for the (file
,line
) (which must exist) that isenabled
, for whichcheckfuncname()
is True, and that has neither a Falsecondition
nor positiveignore
count. The flag, meaning that a temporary breakpoint should be deleted, is False only when thecond
cannot be evaluated (in which case,ignore
count is ignored).If no such entry exists, then (None, None) is returned.