1 | n/a | #! /usr/bin/env python3 |
---|
2 | n/a | |
---|
3 | n/a | """ |
---|
4 | n/a | The Python Debugger Pdb |
---|
5 | n/a | ======================= |
---|
6 | n/a | |
---|
7 | n/a | To use the debugger in its simplest form: |
---|
8 | n/a | |
---|
9 | n/a | >>> import pdb |
---|
10 | n/a | >>> pdb.run('<a statement>') |
---|
11 | n/a | |
---|
12 | n/a | The debugger's prompt is '(Pdb) '. This will stop in the first |
---|
13 | n/a | function call in <a statement>. |
---|
14 | n/a | |
---|
15 | n/a | Alternatively, if a statement terminated with an unhandled exception, |
---|
16 | n/a | you can use pdb's post-mortem facility to inspect the contents of the |
---|
17 | n/a | traceback: |
---|
18 | n/a | |
---|
19 | n/a | >>> <a statement> |
---|
20 | n/a | <exception traceback> |
---|
21 | n/a | >>> import pdb |
---|
22 | n/a | >>> pdb.pm() |
---|
23 | n/a | |
---|
24 | n/a | The commands recognized by the debugger are listed in the next |
---|
25 | n/a | section. Most can be abbreviated as indicated; e.g., h(elp) means |
---|
26 | n/a | that 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel', |
---|
27 | n/a | nor as 'H' or 'Help' or 'HELP'). Optional arguments are enclosed in |
---|
28 | n/a | square brackets. Alternatives in the command syntax are separated |
---|
29 | n/a | by a vertical bar (|). |
---|
30 | n/a | |
---|
31 | n/a | A blank line repeats the previous command literally, except for |
---|
32 | n/a | 'list', where it lists the next 11 lines. |
---|
33 | n/a | |
---|
34 | n/a | Commands that the debugger doesn't recognize are assumed to be Python |
---|
35 | n/a | statements and are executed in the context of the program being |
---|
36 | n/a | debugged. Python statements can also be prefixed with an exclamation |
---|
37 | n/a | point ('!'). This is a powerful way to inspect the program being |
---|
38 | n/a | debugged; it is even possible to change variables or call functions. |
---|
39 | n/a | When an exception occurs in such a statement, the exception name is |
---|
40 | n/a | printed but the debugger's state is not changed. |
---|
41 | n/a | |
---|
42 | n/a | The debugger supports aliases, which can save typing. And aliases can |
---|
43 | n/a | have parameters (see the alias help entry) which allows one a certain |
---|
44 | n/a | level of adaptability to the context under examination. |
---|
45 | n/a | |
---|
46 | n/a | Multiple commands may be entered on a single line, separated by the |
---|
47 | n/a | pair ';;'. No intelligence is applied to separating the commands; the |
---|
48 | n/a | input is split at the first ';;', even if it is in the middle of a |
---|
49 | n/a | quoted string. |
---|
50 | n/a | |
---|
51 | n/a | If a file ".pdbrc" exists in your home directory or in the current |
---|
52 | n/a | directory, it is read in and executed as if it had been typed at the |
---|
53 | n/a | debugger prompt. This is particularly useful for aliases. If both |
---|
54 | n/a | files exist, the one in the home directory is read first and aliases |
---|
55 | n/a | defined there can be overridden by the local file. This behavior can be |
---|
56 | n/a | disabled by passing the "readrc=False" argument to the Pdb constructor. |
---|
57 | n/a | |
---|
58 | n/a | Aside from aliases, the debugger is not directly programmable; but it |
---|
59 | n/a | is implemented as a class from which you can derive your own debugger |
---|
60 | n/a | class, which you can make as fancy as you like. |
---|
61 | n/a | |
---|
62 | n/a | |
---|
63 | n/a | Debugger commands |
---|
64 | n/a | ================= |
---|
65 | n/a | |
---|
66 | n/a | """ |
---|
67 | n/a | # NOTE: the actual command documentation is collected from docstrings of the |
---|
68 | n/a | # commands and is appended to __doc__ after the class has been defined. |
---|
69 | n/a | |
---|
70 | n/a | import os |
---|
71 | n/a | import re |
---|
72 | n/a | import sys |
---|
73 | n/a | import cmd |
---|
74 | n/a | import bdb |
---|
75 | n/a | import dis |
---|
76 | n/a | import code |
---|
77 | n/a | import glob |
---|
78 | n/a | import pprint |
---|
79 | n/a | import signal |
---|
80 | n/a | import inspect |
---|
81 | n/a | import traceback |
---|
82 | n/a | import linecache |
---|
83 | n/a | |
---|
84 | n/a | |
---|
85 | n/a | class Restart(Exception): |
---|
86 | n/a | """Causes a debugger to be restarted for the debugged python program.""" |
---|
87 | n/a | pass |
---|
88 | n/a | |
---|
89 | n/a | __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace", |
---|
90 | n/a | "post_mortem", "help"] |
---|
91 | n/a | |
---|
92 | n/a | def find_function(funcname, filename): |
---|
93 | n/a | cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname)) |
---|
94 | n/a | try: |
---|
95 | n/a | fp = open(filename) |
---|
96 | n/a | except OSError: |
---|
97 | n/a | return None |
---|
98 | n/a | # consumer of this info expects the first line to be 1 |
---|
99 | n/a | with fp: |
---|
100 | n/a | for lineno, line in enumerate(fp, start=1): |
---|
101 | n/a | if cre.match(line): |
---|
102 | n/a | return funcname, filename, lineno |
---|
103 | n/a | return None |
---|
104 | n/a | |
---|
105 | n/a | def getsourcelines(obj): |
---|
106 | n/a | lines, lineno = inspect.findsource(obj) |
---|
107 | n/a | if inspect.isframe(obj) and obj.f_globals is obj.f_locals: |
---|
108 | n/a | # must be a module frame: do not try to cut a block out of it |
---|
109 | n/a | return lines, 1 |
---|
110 | n/a | elif inspect.ismodule(obj): |
---|
111 | n/a | return lines, 1 |
---|
112 | n/a | return inspect.getblock(lines[lineno:]), lineno+1 |
---|
113 | n/a | |
---|
114 | n/a | def lasti2lineno(code, lasti): |
---|
115 | n/a | linestarts = list(dis.findlinestarts(code)) |
---|
116 | n/a | linestarts.reverse() |
---|
117 | n/a | for i, lineno in linestarts: |
---|
118 | n/a | if lasti >= i: |
---|
119 | n/a | return lineno |
---|
120 | n/a | return 0 |
---|
121 | n/a | |
---|
122 | n/a | |
---|
123 | n/a | class _rstr(str): |
---|
124 | n/a | """String that doesn't quote its repr.""" |
---|
125 | n/a | def __repr__(self): |
---|
126 | n/a | return self |
---|
127 | n/a | |
---|
128 | n/a | |
---|
129 | n/a | # Interaction prompt line will separate file and call info from code |
---|
130 | n/a | # text using value of line_prefix string. A newline and arrow may |
---|
131 | n/a | # be to your liking. You can set it once pdb is imported using the |
---|
132 | n/a | # command "pdb.line_prefix = '\n% '". |
---|
133 | n/a | # line_prefix = ': ' # Use this to get the old situation back |
---|
134 | n/a | line_prefix = '\n-> ' # Probably a better default |
---|
135 | n/a | |
---|
136 | n/a | class Pdb(bdb.Bdb, cmd.Cmd): |
---|
137 | n/a | |
---|
138 | n/a | _previous_sigint_handler = None |
---|
139 | n/a | |
---|
140 | n/a | def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None, |
---|
141 | n/a | nosigint=False, readrc=True): |
---|
142 | n/a | bdb.Bdb.__init__(self, skip=skip) |
---|
143 | n/a | cmd.Cmd.__init__(self, completekey, stdin, stdout) |
---|
144 | n/a | if stdout: |
---|
145 | n/a | self.use_rawinput = 0 |
---|
146 | n/a | self.prompt = '(Pdb) ' |
---|
147 | n/a | self.aliases = {} |
---|
148 | n/a | self.displaying = {} |
---|
149 | n/a | self.mainpyfile = '' |
---|
150 | n/a | self._wait_for_mainpyfile = False |
---|
151 | n/a | self.tb_lineno = {} |
---|
152 | n/a | # Try to load readline if it exists |
---|
153 | n/a | try: |
---|
154 | n/a | import readline |
---|
155 | n/a | # remove some common file name delimiters |
---|
156 | n/a | readline.set_completer_delims(' \t\n`@#$%^&*()=+[{]}\\|;:\'",<>?') |
---|
157 | n/a | except ImportError: |
---|
158 | n/a | pass |
---|
159 | n/a | self.allow_kbdint = False |
---|
160 | n/a | self.nosigint = nosigint |
---|
161 | n/a | |
---|
162 | n/a | # Read $HOME/.pdbrc and ./.pdbrc |
---|
163 | n/a | self.rcLines = [] |
---|
164 | n/a | if readrc: |
---|
165 | n/a | if 'HOME' in os.environ: |
---|
166 | n/a | envHome = os.environ['HOME'] |
---|
167 | n/a | try: |
---|
168 | n/a | with open(os.path.join(envHome, ".pdbrc")) as rcFile: |
---|
169 | n/a | self.rcLines.extend(rcFile) |
---|
170 | n/a | except OSError: |
---|
171 | n/a | pass |
---|
172 | n/a | try: |
---|
173 | n/a | with open(".pdbrc") as rcFile: |
---|
174 | n/a | self.rcLines.extend(rcFile) |
---|
175 | n/a | except OSError: |
---|
176 | n/a | pass |
---|
177 | n/a | |
---|
178 | n/a | self.commands = {} # associates a command list to breakpoint numbers |
---|
179 | n/a | self.commands_doprompt = {} # for each bp num, tells if the prompt |
---|
180 | n/a | # must be disp. after execing the cmd list |
---|
181 | n/a | self.commands_silent = {} # for each bp num, tells if the stack trace |
---|
182 | n/a | # must be disp. after execing the cmd list |
---|
183 | n/a | self.commands_defining = False # True while in the process of defining |
---|
184 | n/a | # a command list |
---|
185 | n/a | self.commands_bnum = None # The breakpoint number for which we are |
---|
186 | n/a | # defining a list |
---|
187 | n/a | |
---|
188 | n/a | def sigint_handler(self, signum, frame): |
---|
189 | n/a | if self.allow_kbdint: |
---|
190 | n/a | raise KeyboardInterrupt |
---|
191 | n/a | self.message("\nProgram interrupted. (Use 'cont' to resume).") |
---|
192 | n/a | self.set_step() |
---|
193 | n/a | self.set_trace(frame) |
---|
194 | n/a | |
---|
195 | n/a | def reset(self): |
---|
196 | n/a | bdb.Bdb.reset(self) |
---|
197 | n/a | self.forget() |
---|
198 | n/a | |
---|
199 | n/a | def forget(self): |
---|
200 | n/a | self.lineno = None |
---|
201 | n/a | self.stack = [] |
---|
202 | n/a | self.curindex = 0 |
---|
203 | n/a | self.curframe = None |
---|
204 | n/a | self.tb_lineno.clear() |
---|
205 | n/a | |
---|
206 | n/a | def setup(self, f, tb): |
---|
207 | n/a | self.forget() |
---|
208 | n/a | self.stack, self.curindex = self.get_stack(f, tb) |
---|
209 | n/a | while tb: |
---|
210 | n/a | # when setting up post-mortem debugging with a traceback, save all |
---|
211 | n/a | # the original line numbers to be displayed along the current line |
---|
212 | n/a | # numbers (which can be different, e.g. due to finally clauses) |
---|
213 | n/a | lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti) |
---|
214 | n/a | self.tb_lineno[tb.tb_frame] = lineno |
---|
215 | n/a | tb = tb.tb_next |
---|
216 | n/a | self.curframe = self.stack[self.curindex][0] |
---|
217 | n/a | # The f_locals dictionary is updated from the actual frame |
---|
218 | n/a | # locals whenever the .f_locals accessor is called, so we |
---|
219 | n/a | # cache it here to ensure that modifications are not overwritten. |
---|
220 | n/a | self.curframe_locals = self.curframe.f_locals |
---|
221 | n/a | return self.execRcLines() |
---|
222 | n/a | |
---|
223 | n/a | # Can be executed earlier than 'setup' if desired |
---|
224 | n/a | def execRcLines(self): |
---|
225 | n/a | if not self.rcLines: |
---|
226 | n/a | return |
---|
227 | n/a | # local copy because of recursion |
---|
228 | n/a | rcLines = self.rcLines |
---|
229 | n/a | rcLines.reverse() |
---|
230 | n/a | # execute every line only once |
---|
231 | n/a | self.rcLines = [] |
---|
232 | n/a | while rcLines: |
---|
233 | n/a | line = rcLines.pop().strip() |
---|
234 | n/a | if line and line[0] != '#': |
---|
235 | n/a | if self.onecmd(line): |
---|
236 | n/a | # if onecmd returns True, the command wants to exit |
---|
237 | n/a | # from the interaction, save leftover rc lines |
---|
238 | n/a | # to execute before next interaction |
---|
239 | n/a | self.rcLines += reversed(rcLines) |
---|
240 | n/a | return True |
---|
241 | n/a | |
---|
242 | n/a | # Override Bdb methods |
---|
243 | n/a | |
---|
244 | n/a | def user_call(self, frame, argument_list): |
---|
245 | n/a | """This method is called when there is the remote possibility |
---|
246 | n/a | that we ever need to stop in this function.""" |
---|
247 | n/a | if self._wait_for_mainpyfile: |
---|
248 | n/a | return |
---|
249 | n/a | if self.stop_here(frame): |
---|
250 | n/a | self.message('--Call--') |
---|
251 | n/a | self.interaction(frame, None) |
---|
252 | n/a | |
---|
253 | n/a | def user_line(self, frame): |
---|
254 | n/a | """This function is called when we stop or break at this line.""" |
---|
255 | n/a | if self._wait_for_mainpyfile: |
---|
256 | n/a | if (self.mainpyfile != self.canonic(frame.f_code.co_filename) |
---|
257 | n/a | or frame.f_lineno <= 0): |
---|
258 | n/a | return |
---|
259 | n/a | self._wait_for_mainpyfile = False |
---|
260 | n/a | if self.bp_commands(frame): |
---|
261 | n/a | self.interaction(frame, None) |
---|
262 | n/a | |
---|
263 | n/a | def bp_commands(self, frame): |
---|
264 | n/a | """Call every command that was set for the current active breakpoint |
---|
265 | n/a | (if there is one). |
---|
266 | n/a | |
---|
267 | n/a | Returns True if the normal interaction function must be called, |
---|
268 | n/a | False otherwise.""" |
---|
269 | n/a | # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit |
---|
270 | n/a | if getattr(self, "currentbp", False) and \ |
---|
271 | n/a | self.currentbp in self.commands: |
---|
272 | n/a | currentbp = self.currentbp |
---|
273 | n/a | self.currentbp = 0 |
---|
274 | n/a | lastcmd_back = self.lastcmd |
---|
275 | n/a | self.setup(frame, None) |
---|
276 | n/a | for line in self.commands[currentbp]: |
---|
277 | n/a | self.onecmd(line) |
---|
278 | n/a | self.lastcmd = lastcmd_back |
---|
279 | n/a | if not self.commands_silent[currentbp]: |
---|
280 | n/a | self.print_stack_entry(self.stack[self.curindex]) |
---|
281 | n/a | if self.commands_doprompt[currentbp]: |
---|
282 | n/a | self._cmdloop() |
---|
283 | n/a | self.forget() |
---|
284 | n/a | return |
---|
285 | n/a | return 1 |
---|
286 | n/a | |
---|
287 | n/a | def user_return(self, frame, return_value): |
---|
288 | n/a | """This function is called when a return trap is set here.""" |
---|
289 | n/a | if self._wait_for_mainpyfile: |
---|
290 | n/a | return |
---|
291 | n/a | frame.f_locals['__return__'] = return_value |
---|
292 | n/a | self.message('--Return--') |
---|
293 | n/a | self.interaction(frame, None) |
---|
294 | n/a | |
---|
295 | n/a | def user_exception(self, frame, exc_info): |
---|
296 | n/a | """This function is called if an exception occurs, |
---|
297 | n/a | but only if we are to stop at or just below this level.""" |
---|
298 | n/a | if self._wait_for_mainpyfile: |
---|
299 | n/a | return |
---|
300 | n/a | exc_type, exc_value, exc_traceback = exc_info |
---|
301 | n/a | frame.f_locals['__exception__'] = exc_type, exc_value |
---|
302 | n/a | |
---|
303 | n/a | # An 'Internal StopIteration' exception is an exception debug event |
---|
304 | n/a | # issued by the interpreter when handling a subgenerator run with |
---|
305 | n/a | # 'yield from' or a generator controlled by a for loop. No exception has |
---|
306 | n/a | # actually occurred in this case. The debugger uses this debug event to |
---|
307 | n/a | # stop when the debuggee is returning from such generators. |
---|
308 | n/a | prefix = 'Internal ' if (not exc_traceback |
---|
309 | n/a | and exc_type is StopIteration) else '' |
---|
310 | n/a | self.message('%s%s' % (prefix, |
---|
311 | n/a | traceback.format_exception_only(exc_type, exc_value)[-1].strip())) |
---|
312 | n/a | self.interaction(frame, exc_traceback) |
---|
313 | n/a | |
---|
314 | n/a | # General interaction function |
---|
315 | n/a | def _cmdloop(self): |
---|
316 | n/a | while True: |
---|
317 | n/a | try: |
---|
318 | n/a | # keyboard interrupts allow for an easy way to cancel |
---|
319 | n/a | # the current command, so allow them during interactive input |
---|
320 | n/a | self.allow_kbdint = True |
---|
321 | n/a | self.cmdloop() |
---|
322 | n/a | self.allow_kbdint = False |
---|
323 | n/a | break |
---|
324 | n/a | except KeyboardInterrupt: |
---|
325 | n/a | self.message('--KeyboardInterrupt--') |
---|
326 | n/a | |
---|
327 | n/a | # Called before loop, handles display expressions |
---|
328 | n/a | def preloop(self): |
---|
329 | n/a | displaying = self.displaying.get(self.curframe) |
---|
330 | n/a | if displaying: |
---|
331 | n/a | for expr, oldvalue in displaying.items(): |
---|
332 | n/a | newvalue = self._getval_except(expr) |
---|
333 | n/a | # check for identity first; this prevents custom __eq__ to |
---|
334 | n/a | # be called at every loop, and also prevents instances whose |
---|
335 | n/a | # fields are changed to be displayed |
---|
336 | n/a | if newvalue is not oldvalue and newvalue != oldvalue: |
---|
337 | n/a | displaying[expr] = newvalue |
---|
338 | n/a | self.message('display %s: %r [old: %r]' % |
---|
339 | n/a | (expr, newvalue, oldvalue)) |
---|
340 | n/a | |
---|
341 | n/a | def interaction(self, frame, traceback): |
---|
342 | n/a | # Restore the previous signal handler at the Pdb prompt. |
---|
343 | n/a | if Pdb._previous_sigint_handler: |
---|
344 | n/a | signal.signal(signal.SIGINT, Pdb._previous_sigint_handler) |
---|
345 | n/a | Pdb._previous_sigint_handler = None |
---|
346 | n/a | if self.setup(frame, traceback): |
---|
347 | n/a | # no interaction desired at this time (happens if .pdbrc contains |
---|
348 | n/a | # a command like "continue") |
---|
349 | n/a | self.forget() |
---|
350 | n/a | return |
---|
351 | n/a | self.print_stack_entry(self.stack[self.curindex]) |
---|
352 | n/a | self._cmdloop() |
---|
353 | n/a | self.forget() |
---|
354 | n/a | |
---|
355 | n/a | def displayhook(self, obj): |
---|
356 | n/a | """Custom displayhook for the exec in default(), which prevents |
---|
357 | n/a | assignment of the _ variable in the builtins. |
---|
358 | n/a | """ |
---|
359 | n/a | # reproduce the behavior of the standard displayhook, not printing None |
---|
360 | n/a | if obj is not None: |
---|
361 | n/a | self.message(repr(obj)) |
---|
362 | n/a | |
---|
363 | n/a | def default(self, line): |
---|
364 | n/a | if line[:1] == '!': line = line[1:] |
---|
365 | n/a | locals = self.curframe_locals |
---|
366 | n/a | globals = self.curframe.f_globals |
---|
367 | n/a | try: |
---|
368 | n/a | code = compile(line + '\n', '<stdin>', 'single') |
---|
369 | n/a | save_stdout = sys.stdout |
---|
370 | n/a | save_stdin = sys.stdin |
---|
371 | n/a | save_displayhook = sys.displayhook |
---|
372 | n/a | try: |
---|
373 | n/a | sys.stdin = self.stdin |
---|
374 | n/a | sys.stdout = self.stdout |
---|
375 | n/a | sys.displayhook = self.displayhook |
---|
376 | n/a | exec(code, globals, locals) |
---|
377 | n/a | finally: |
---|
378 | n/a | sys.stdout = save_stdout |
---|
379 | n/a | sys.stdin = save_stdin |
---|
380 | n/a | sys.displayhook = save_displayhook |
---|
381 | n/a | except: |
---|
382 | n/a | exc_info = sys.exc_info()[:2] |
---|
383 | n/a | self.error(traceback.format_exception_only(*exc_info)[-1].strip()) |
---|
384 | n/a | |
---|
385 | n/a | def precmd(self, line): |
---|
386 | n/a | """Handle alias expansion and ';;' separator.""" |
---|
387 | n/a | if not line.strip(): |
---|
388 | n/a | return line |
---|
389 | n/a | args = line.split() |
---|
390 | n/a | while args[0] in self.aliases: |
---|
391 | n/a | line = self.aliases[args[0]] |
---|
392 | n/a | ii = 1 |
---|
393 | n/a | for tmpArg in args[1:]: |
---|
394 | n/a | line = line.replace("%" + str(ii), |
---|
395 | n/a | tmpArg) |
---|
396 | n/a | ii += 1 |
---|
397 | n/a | line = line.replace("%*", ' '.join(args[1:])) |
---|
398 | n/a | args = line.split() |
---|
399 | n/a | # split into ';;' separated commands |
---|
400 | n/a | # unless it's an alias command |
---|
401 | n/a | if args[0] != 'alias': |
---|
402 | n/a | marker = line.find(';;') |
---|
403 | n/a | if marker >= 0: |
---|
404 | n/a | # queue up everything after marker |
---|
405 | n/a | next = line[marker+2:].lstrip() |
---|
406 | n/a | self.cmdqueue.append(next) |
---|
407 | n/a | line = line[:marker].rstrip() |
---|
408 | n/a | return line |
---|
409 | n/a | |
---|
410 | n/a | def onecmd(self, line): |
---|
411 | n/a | """Interpret the argument as though it had been typed in response |
---|
412 | n/a | to the prompt. |
---|
413 | n/a | |
---|
414 | n/a | Checks whether this line is typed at the normal prompt or in |
---|
415 | n/a | a breakpoint command list definition. |
---|
416 | n/a | """ |
---|
417 | n/a | if not self.commands_defining: |
---|
418 | n/a | return cmd.Cmd.onecmd(self, line) |
---|
419 | n/a | else: |
---|
420 | n/a | return self.handle_command_def(line) |
---|
421 | n/a | |
---|
422 | n/a | def handle_command_def(self, line): |
---|
423 | n/a | """Handles one command line during command list definition.""" |
---|
424 | n/a | cmd, arg, line = self.parseline(line) |
---|
425 | n/a | if not cmd: |
---|
426 | n/a | return |
---|
427 | n/a | if cmd == 'silent': |
---|
428 | n/a | self.commands_silent[self.commands_bnum] = True |
---|
429 | n/a | return # continue to handle other cmd def in the cmd list |
---|
430 | n/a | elif cmd == 'end': |
---|
431 | n/a | self.cmdqueue = [] |
---|
432 | n/a | return 1 # end of cmd list |
---|
433 | n/a | cmdlist = self.commands[self.commands_bnum] |
---|
434 | n/a | if arg: |
---|
435 | n/a | cmdlist.append(cmd+' '+arg) |
---|
436 | n/a | else: |
---|
437 | n/a | cmdlist.append(cmd) |
---|
438 | n/a | # Determine if we must stop |
---|
439 | n/a | try: |
---|
440 | n/a | func = getattr(self, 'do_' + cmd) |
---|
441 | n/a | except AttributeError: |
---|
442 | n/a | func = self.default |
---|
443 | n/a | # one of the resuming commands |
---|
444 | n/a | if func.__name__ in self.commands_resuming: |
---|
445 | n/a | self.commands_doprompt[self.commands_bnum] = False |
---|
446 | n/a | self.cmdqueue = [] |
---|
447 | n/a | return 1 |
---|
448 | n/a | return |
---|
449 | n/a | |
---|
450 | n/a | # interface abstraction functions |
---|
451 | n/a | |
---|
452 | n/a | def message(self, msg): |
---|
453 | n/a | print(msg, file=self.stdout) |
---|
454 | n/a | |
---|
455 | n/a | def error(self, msg): |
---|
456 | n/a | print('***', msg, file=self.stdout) |
---|
457 | n/a | |
---|
458 | n/a | # Generic completion functions. Individual complete_foo methods can be |
---|
459 | n/a | # assigned below to one of these functions. |
---|
460 | n/a | |
---|
461 | n/a | def _complete_location(self, text, line, begidx, endidx): |
---|
462 | n/a | # Complete a file/module/function location for break/tbreak/clear. |
---|
463 | n/a | if line.strip().endswith((':', ',')): |
---|
464 | n/a | # Here comes a line number or a condition which we can't complete. |
---|
465 | n/a | return [] |
---|
466 | n/a | # First, try to find matching functions (i.e. expressions). |
---|
467 | n/a | try: |
---|
468 | n/a | ret = self._complete_expression(text, line, begidx, endidx) |
---|
469 | n/a | except Exception: |
---|
470 | n/a | ret = [] |
---|
471 | n/a | # Then, try to complete file names as well. |
---|
472 | n/a | globs = glob.glob(text + '*') |
---|
473 | n/a | for fn in globs: |
---|
474 | n/a | if os.path.isdir(fn): |
---|
475 | n/a | ret.append(fn + '/') |
---|
476 | n/a | elif os.path.isfile(fn) and fn.lower().endswith(('.py', '.pyw')): |
---|
477 | n/a | ret.append(fn + ':') |
---|
478 | n/a | return ret |
---|
479 | n/a | |
---|
480 | n/a | def _complete_bpnumber(self, text, line, begidx, endidx): |
---|
481 | n/a | # Complete a breakpoint number. (This would be more helpful if we could |
---|
482 | n/a | # display additional info along with the completions, such as file/line |
---|
483 | n/a | # of the breakpoint.) |
---|
484 | n/a | return [str(i) for i, bp in enumerate(bdb.Breakpoint.bpbynumber) |
---|
485 | n/a | if bp is not None and str(i).startswith(text)] |
---|
486 | n/a | |
---|
487 | n/a | def _complete_expression(self, text, line, begidx, endidx): |
---|
488 | n/a | # Complete an arbitrary expression. |
---|
489 | n/a | if not self.curframe: |
---|
490 | n/a | return [] |
---|
491 | n/a | # Collect globals and locals. It is usually not really sensible to also |
---|
492 | n/a | # complete builtins, and they clutter the namespace quite heavily, so we |
---|
493 | n/a | # leave them out. |
---|
494 | n/a | ns = self.curframe.f_globals.copy() |
---|
495 | n/a | ns.update(self.curframe_locals) |
---|
496 | n/a | if '.' in text: |
---|
497 | n/a | # Walk an attribute chain up to the last part, similar to what |
---|
498 | n/a | # rlcompleter does. This will bail if any of the parts are not |
---|
499 | n/a | # simple attribute access, which is what we want. |
---|
500 | n/a | dotted = text.split('.') |
---|
501 | n/a | try: |
---|
502 | n/a | obj = ns[dotted[0]] |
---|
503 | n/a | for part in dotted[1:-1]: |
---|
504 | n/a | obj = getattr(obj, part) |
---|
505 | n/a | except (KeyError, AttributeError): |
---|
506 | n/a | return [] |
---|
507 | n/a | prefix = '.'.join(dotted[:-1]) + '.' |
---|
508 | n/a | return [prefix + n for n in dir(obj) if n.startswith(dotted[-1])] |
---|
509 | n/a | else: |
---|
510 | n/a | # Complete a simple name. |
---|
511 | n/a | return [n for n in ns.keys() if n.startswith(text)] |
---|
512 | n/a | |
---|
513 | n/a | # Command definitions, called by cmdloop() |
---|
514 | n/a | # The argument is the remaining string on the command line |
---|
515 | n/a | # Return true to exit from the command loop |
---|
516 | n/a | |
---|
517 | n/a | def do_commands(self, arg): |
---|
518 | n/a | """commands [bpnumber] |
---|
519 | n/a | (com) ... |
---|
520 | n/a | (com) end |
---|
521 | n/a | (Pdb) |
---|
522 | n/a | |
---|
523 | n/a | Specify a list of commands for breakpoint number bpnumber. |
---|
524 | n/a | The commands themselves are entered on the following lines. |
---|
525 | n/a | Type a line containing just 'end' to terminate the commands. |
---|
526 | n/a | The commands are executed when the breakpoint is hit. |
---|
527 | n/a | |
---|
528 | n/a | To remove all commands from a breakpoint, type commands and |
---|
529 | n/a | follow it immediately with end; that is, give no commands. |
---|
530 | n/a | |
---|
531 | n/a | With no bpnumber argument, commands refers to the last |
---|
532 | n/a | breakpoint set. |
---|
533 | n/a | |
---|
534 | n/a | You can use breakpoint commands to start your program up |
---|
535 | n/a | again. Simply use the continue command, or step, or any other |
---|
536 | n/a | command that resumes execution. |
---|
537 | n/a | |
---|
538 | n/a | Specifying any command resuming execution (currently continue, |
---|
539 | n/a | step, next, return, jump, quit and their abbreviations) |
---|
540 | n/a | terminates the command list (as if that command was |
---|
541 | n/a | immediately followed by end). This is because any time you |
---|
542 | n/a | resume execution (even with a simple next or step), you may |
---|
543 | n/a | encounter another breakpoint -- which could have its own |
---|
544 | n/a | command list, leading to ambiguities about which list to |
---|
545 | n/a | execute. |
---|
546 | n/a | |
---|
547 | n/a | If you use the 'silent' command in the command list, the usual |
---|
548 | n/a | message about stopping at a breakpoint is not printed. This |
---|
549 | n/a | may be desirable for breakpoints that are to print a specific |
---|
550 | n/a | message and then continue. If none of the other commands |
---|
551 | n/a | print anything, you will see no sign that the breakpoint was |
---|
552 | n/a | reached. |
---|
553 | n/a | """ |
---|
554 | n/a | if not arg: |
---|
555 | n/a | bnum = len(bdb.Breakpoint.bpbynumber) - 1 |
---|
556 | n/a | else: |
---|
557 | n/a | try: |
---|
558 | n/a | bnum = int(arg) |
---|
559 | n/a | except: |
---|
560 | n/a | self.error("Usage: commands [bnum]\n ...\n end") |
---|
561 | n/a | return |
---|
562 | n/a | self.commands_bnum = bnum |
---|
563 | n/a | # Save old definitions for the case of a keyboard interrupt. |
---|
564 | n/a | if bnum in self.commands: |
---|
565 | n/a | old_command_defs = (self.commands[bnum], |
---|
566 | n/a | self.commands_doprompt[bnum], |
---|
567 | n/a | self.commands_silent[bnum]) |
---|
568 | n/a | else: |
---|
569 | n/a | old_command_defs = None |
---|
570 | n/a | self.commands[bnum] = [] |
---|
571 | n/a | self.commands_doprompt[bnum] = True |
---|
572 | n/a | self.commands_silent[bnum] = False |
---|
573 | n/a | |
---|
574 | n/a | prompt_back = self.prompt |
---|
575 | n/a | self.prompt = '(com) ' |
---|
576 | n/a | self.commands_defining = True |
---|
577 | n/a | try: |
---|
578 | n/a | self.cmdloop() |
---|
579 | n/a | except KeyboardInterrupt: |
---|
580 | n/a | # Restore old definitions. |
---|
581 | n/a | if old_command_defs: |
---|
582 | n/a | self.commands[bnum] = old_command_defs[0] |
---|
583 | n/a | self.commands_doprompt[bnum] = old_command_defs[1] |
---|
584 | n/a | self.commands_silent[bnum] = old_command_defs[2] |
---|
585 | n/a | else: |
---|
586 | n/a | del self.commands[bnum] |
---|
587 | n/a | del self.commands_doprompt[bnum] |
---|
588 | n/a | del self.commands_silent[bnum] |
---|
589 | n/a | self.error('command definition aborted, old commands restored') |
---|
590 | n/a | finally: |
---|
591 | n/a | self.commands_defining = False |
---|
592 | n/a | self.prompt = prompt_back |
---|
593 | n/a | |
---|
594 | n/a | complete_commands = _complete_bpnumber |
---|
595 | n/a | |
---|
596 | n/a | def do_break(self, arg, temporary = 0): |
---|
597 | n/a | """b(reak) [ ([filename:]lineno | function) [, condition] ] |
---|
598 | n/a | Without argument, list all breaks. |
---|
599 | n/a | |
---|
600 | n/a | With a line number argument, set a break at this line in the |
---|
601 | n/a | current file. With a function name, set a break at the first |
---|
602 | n/a | executable line of that function. If a second argument is |
---|
603 | n/a | present, it is a string specifying an expression which must |
---|
604 | n/a | evaluate to true before the breakpoint is honored. |
---|
605 | n/a | |
---|
606 | n/a | The line number may be prefixed with a filename and a colon, |
---|
607 | n/a | to specify a breakpoint in another file (probably one that |
---|
608 | n/a | hasn't been loaded yet). The file is searched for on |
---|
609 | n/a | sys.path; the .py suffix may be omitted. |
---|
610 | n/a | """ |
---|
611 | n/a | if not arg: |
---|
612 | n/a | if self.breaks: # There's at least one |
---|
613 | n/a | self.message("Num Type Disp Enb Where") |
---|
614 | n/a | for bp in bdb.Breakpoint.bpbynumber: |
---|
615 | n/a | if bp: |
---|
616 | n/a | self.message(bp.bpformat()) |
---|
617 | n/a | return |
---|
618 | n/a | # parse arguments; comma has lowest precedence |
---|
619 | n/a | # and cannot occur in filename |
---|
620 | n/a | filename = None |
---|
621 | n/a | lineno = None |
---|
622 | n/a | cond = None |
---|
623 | n/a | comma = arg.find(',') |
---|
624 | n/a | if comma > 0: |
---|
625 | n/a | # parse stuff after comma: "condition" |
---|
626 | n/a | cond = arg[comma+1:].lstrip() |
---|
627 | n/a | arg = arg[:comma].rstrip() |
---|
628 | n/a | # parse stuff before comma: [filename:]lineno | function |
---|
629 | n/a | colon = arg.rfind(':') |
---|
630 | n/a | funcname = None |
---|
631 | n/a | if colon >= 0: |
---|
632 | n/a | filename = arg[:colon].rstrip() |
---|
633 | n/a | f = self.lookupmodule(filename) |
---|
634 | n/a | if not f: |
---|
635 | n/a | self.error('%r not found from sys.path' % filename) |
---|
636 | n/a | return |
---|
637 | n/a | else: |
---|
638 | n/a | filename = f |
---|
639 | n/a | arg = arg[colon+1:].lstrip() |
---|
640 | n/a | try: |
---|
641 | n/a | lineno = int(arg) |
---|
642 | n/a | except ValueError: |
---|
643 | n/a | self.error('Bad lineno: %s' % arg) |
---|
644 | n/a | return |
---|
645 | n/a | else: |
---|
646 | n/a | # no colon; can be lineno or function |
---|
647 | n/a | try: |
---|
648 | n/a | lineno = int(arg) |
---|
649 | n/a | except ValueError: |
---|
650 | n/a | try: |
---|
651 | n/a | func = eval(arg, |
---|
652 | n/a | self.curframe.f_globals, |
---|
653 | n/a | self.curframe_locals) |
---|
654 | n/a | except: |
---|
655 | n/a | func = arg |
---|
656 | n/a | try: |
---|
657 | n/a | if hasattr(func, '__func__'): |
---|
658 | n/a | func = func.__func__ |
---|
659 | n/a | code = func.__code__ |
---|
660 | n/a | #use co_name to identify the bkpt (function names |
---|
661 | n/a | #could be aliased, but co_name is invariant) |
---|
662 | n/a | funcname = code.co_name |
---|
663 | n/a | lineno = code.co_firstlineno |
---|
664 | n/a | filename = code.co_filename |
---|
665 | n/a | except: |
---|
666 | n/a | # last thing to try |
---|
667 | n/a | (ok, filename, ln) = self.lineinfo(arg) |
---|
668 | n/a | if not ok: |
---|
669 | n/a | self.error('The specified object %r is not a function ' |
---|
670 | n/a | 'or was not found along sys.path.' % arg) |
---|
671 | n/a | return |
---|
672 | n/a | funcname = ok # ok contains a function name |
---|
673 | n/a | lineno = int(ln) |
---|
674 | n/a | if not filename: |
---|
675 | n/a | filename = self.defaultFile() |
---|
676 | n/a | # Check for reasonable breakpoint |
---|
677 | n/a | line = self.checkline(filename, lineno) |
---|
678 | n/a | if line: |
---|
679 | n/a | # now set the break point |
---|
680 | n/a | err = self.set_break(filename, line, temporary, cond, funcname) |
---|
681 | n/a | if err: |
---|
682 | n/a | self.error(err) |
---|
683 | n/a | else: |
---|
684 | n/a | bp = self.get_breaks(filename, line)[-1] |
---|
685 | n/a | self.message("Breakpoint %d at %s:%d" % |
---|
686 | n/a | (bp.number, bp.file, bp.line)) |
---|
687 | n/a | |
---|
688 | n/a | # To be overridden in derived debuggers |
---|
689 | n/a | def defaultFile(self): |
---|
690 | n/a | """Produce a reasonable default.""" |
---|
691 | n/a | filename = self.curframe.f_code.co_filename |
---|
692 | n/a | if filename == '<string>' and self.mainpyfile: |
---|
693 | n/a | filename = self.mainpyfile |
---|
694 | n/a | return filename |
---|
695 | n/a | |
---|
696 | n/a | do_b = do_break |
---|
697 | n/a | |
---|
698 | n/a | complete_break = _complete_location |
---|
699 | n/a | complete_b = _complete_location |
---|
700 | n/a | |
---|
701 | n/a | def do_tbreak(self, arg): |
---|
702 | n/a | """tbreak [ ([filename:]lineno | function) [, condition] ] |
---|
703 | n/a | Same arguments as break, but sets a temporary breakpoint: it |
---|
704 | n/a | is automatically deleted when first hit. |
---|
705 | n/a | """ |
---|
706 | n/a | self.do_break(arg, 1) |
---|
707 | n/a | |
---|
708 | n/a | complete_tbreak = _complete_location |
---|
709 | n/a | |
---|
710 | n/a | def lineinfo(self, identifier): |
---|
711 | n/a | failed = (None, None, None) |
---|
712 | n/a | # Input is identifier, may be in single quotes |
---|
713 | n/a | idstring = identifier.split("'") |
---|
714 | n/a | if len(idstring) == 1: |
---|
715 | n/a | # not in single quotes |
---|
716 | n/a | id = idstring[0].strip() |
---|
717 | n/a | elif len(idstring) == 3: |
---|
718 | n/a | # quoted |
---|
719 | n/a | id = idstring[1].strip() |
---|
720 | n/a | else: |
---|
721 | n/a | return failed |
---|
722 | n/a | if id == '': return failed |
---|
723 | n/a | parts = id.split('.') |
---|
724 | n/a | # Protection for derived debuggers |
---|
725 | n/a | if parts[0] == 'self': |
---|
726 | n/a | del parts[0] |
---|
727 | n/a | if len(parts) == 0: |
---|
728 | n/a | return failed |
---|
729 | n/a | # Best first guess at file to look at |
---|
730 | n/a | fname = self.defaultFile() |
---|
731 | n/a | if len(parts) == 1: |
---|
732 | n/a | item = parts[0] |
---|
733 | n/a | else: |
---|
734 | n/a | # More than one part. |
---|
735 | n/a | # First is module, second is method/class |
---|
736 | n/a | f = self.lookupmodule(parts[0]) |
---|
737 | n/a | if f: |
---|
738 | n/a | fname = f |
---|
739 | n/a | item = parts[1] |
---|
740 | n/a | answer = find_function(item, fname) |
---|
741 | n/a | return answer or failed |
---|
742 | n/a | |
---|
743 | n/a | def checkline(self, filename, lineno): |
---|
744 | n/a | """Check whether specified line seems to be executable. |
---|
745 | n/a | |
---|
746 | n/a | Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank |
---|
747 | n/a | line or EOF). Warning: testing is not comprehensive. |
---|
748 | n/a | """ |
---|
749 | n/a | # this method should be callable before starting debugging, so default |
---|
750 | n/a | # to "no globals" if there is no current frame |
---|
751 | n/a | globs = self.curframe.f_globals if hasattr(self, 'curframe') else None |
---|
752 | n/a | line = linecache.getline(filename, lineno, globs) |
---|
753 | n/a | if not line: |
---|
754 | n/a | self.message('End of file') |
---|
755 | n/a | return 0 |
---|
756 | n/a | line = line.strip() |
---|
757 | n/a | # Don't allow setting breakpoint at a blank line |
---|
758 | n/a | if (not line or (line[0] == '#') or |
---|
759 | n/a | (line[:3] == '"""') or line[:3] == "'''"): |
---|
760 | n/a | self.error('Blank or comment') |
---|
761 | n/a | return 0 |
---|
762 | n/a | return lineno |
---|
763 | n/a | |
---|
764 | n/a | def do_enable(self, arg): |
---|
765 | n/a | """enable bpnumber [bpnumber ...] |
---|
766 | n/a | Enables the breakpoints given as a space separated list of |
---|
767 | n/a | breakpoint numbers. |
---|
768 | n/a | """ |
---|
769 | n/a | args = arg.split() |
---|
770 | n/a | for i in args: |
---|
771 | n/a | try: |
---|
772 | n/a | bp = self.get_bpbynumber(i) |
---|
773 | n/a | except ValueError as err: |
---|
774 | n/a | self.error(err) |
---|
775 | n/a | else: |
---|
776 | n/a | bp.enable() |
---|
777 | n/a | self.message('Enabled %s' % bp) |
---|
778 | n/a | |
---|
779 | n/a | complete_enable = _complete_bpnumber |
---|
780 | n/a | |
---|
781 | n/a | def do_disable(self, arg): |
---|
782 | n/a | """disable bpnumber [bpnumber ...] |
---|
783 | n/a | Disables the breakpoints given as a space separated list of |
---|
784 | n/a | breakpoint numbers. Disabling a breakpoint means it cannot |
---|
785 | n/a | cause the program to stop execution, but unlike clearing a |
---|
786 | n/a | breakpoint, it remains in the list of breakpoints and can be |
---|
787 | n/a | (re-)enabled. |
---|
788 | n/a | """ |
---|
789 | n/a | args = arg.split() |
---|
790 | n/a | for i in args: |
---|
791 | n/a | try: |
---|
792 | n/a | bp = self.get_bpbynumber(i) |
---|
793 | n/a | except ValueError as err: |
---|
794 | n/a | self.error(err) |
---|
795 | n/a | else: |
---|
796 | n/a | bp.disable() |
---|
797 | n/a | self.message('Disabled %s' % bp) |
---|
798 | n/a | |
---|
799 | n/a | complete_disable = _complete_bpnumber |
---|
800 | n/a | |
---|
801 | n/a | def do_condition(self, arg): |
---|
802 | n/a | """condition bpnumber [condition] |
---|
803 | n/a | Set a new condition for the breakpoint, an expression which |
---|
804 | n/a | must evaluate to true before the breakpoint is honored. If |
---|
805 | n/a | condition is absent, any existing condition is removed; i.e., |
---|
806 | n/a | the breakpoint is made unconditional. |
---|
807 | n/a | """ |
---|
808 | n/a | args = arg.split(' ', 1) |
---|
809 | n/a | try: |
---|
810 | n/a | cond = args[1] |
---|
811 | n/a | except IndexError: |
---|
812 | n/a | cond = None |
---|
813 | n/a | try: |
---|
814 | n/a | bp = self.get_bpbynumber(args[0].strip()) |
---|
815 | n/a | except IndexError: |
---|
816 | n/a | self.error('Breakpoint number expected') |
---|
817 | n/a | except ValueError as err: |
---|
818 | n/a | self.error(err) |
---|
819 | n/a | else: |
---|
820 | n/a | bp.cond = cond |
---|
821 | n/a | if not cond: |
---|
822 | n/a | self.message('Breakpoint %d is now unconditional.' % bp.number) |
---|
823 | n/a | else: |
---|
824 | n/a | self.message('New condition set for breakpoint %d.' % bp.number) |
---|
825 | n/a | |
---|
826 | n/a | complete_condition = _complete_bpnumber |
---|
827 | n/a | |
---|
828 | n/a | def do_ignore(self, arg): |
---|
829 | n/a | """ignore bpnumber [count] |
---|
830 | n/a | Set the ignore count for the given breakpoint number. If |
---|
831 | n/a | count is omitted, the ignore count is set to 0. A breakpoint |
---|
832 | n/a | becomes active when the ignore count is zero. When non-zero, |
---|
833 | n/a | the count is decremented each time the breakpoint is reached |
---|
834 | n/a | and the breakpoint is not disabled and any associated |
---|
835 | n/a | condition evaluates to true. |
---|
836 | n/a | """ |
---|
837 | n/a | args = arg.split() |
---|
838 | n/a | try: |
---|
839 | n/a | count = int(args[1].strip()) |
---|
840 | n/a | except: |
---|
841 | n/a | count = 0 |
---|
842 | n/a | try: |
---|
843 | n/a | bp = self.get_bpbynumber(args[0].strip()) |
---|
844 | n/a | except IndexError: |
---|
845 | n/a | self.error('Breakpoint number expected') |
---|
846 | n/a | except ValueError as err: |
---|
847 | n/a | self.error(err) |
---|
848 | n/a | else: |
---|
849 | n/a | bp.ignore = count |
---|
850 | n/a | if count > 0: |
---|
851 | n/a | if count > 1: |
---|
852 | n/a | countstr = '%d crossings' % count |
---|
853 | n/a | else: |
---|
854 | n/a | countstr = '1 crossing' |
---|
855 | n/a | self.message('Will ignore next %s of breakpoint %d.' % |
---|
856 | n/a | (countstr, bp.number)) |
---|
857 | n/a | else: |
---|
858 | n/a | self.message('Will stop next time breakpoint %d is reached.' |
---|
859 | n/a | % bp.number) |
---|
860 | n/a | |
---|
861 | n/a | complete_ignore = _complete_bpnumber |
---|
862 | n/a | |
---|
863 | n/a | def do_clear(self, arg): |
---|
864 | n/a | """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]] |
---|
865 | n/a | With a space separated list of breakpoint numbers, clear |
---|
866 | n/a | those breakpoints. Without argument, clear all breaks (but |
---|
867 | n/a | first ask confirmation). With a filename:lineno argument, |
---|
868 | n/a | clear all breaks at that line in that file. |
---|
869 | n/a | """ |
---|
870 | n/a | if not arg: |
---|
871 | n/a | try: |
---|
872 | n/a | reply = input('Clear all breaks? ') |
---|
873 | n/a | except EOFError: |
---|
874 | n/a | reply = 'no' |
---|
875 | n/a | reply = reply.strip().lower() |
---|
876 | n/a | if reply in ('y', 'yes'): |
---|
877 | n/a | bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp] |
---|
878 | n/a | self.clear_all_breaks() |
---|
879 | n/a | for bp in bplist: |
---|
880 | n/a | self.message('Deleted %s' % bp) |
---|
881 | n/a | return |
---|
882 | n/a | if ':' in arg: |
---|
883 | n/a | # Make sure it works for "clear C:\foo\bar.py:12" |
---|
884 | n/a | i = arg.rfind(':') |
---|
885 | n/a | filename = arg[:i] |
---|
886 | n/a | arg = arg[i+1:] |
---|
887 | n/a | try: |
---|
888 | n/a | lineno = int(arg) |
---|
889 | n/a | except ValueError: |
---|
890 | n/a | err = "Invalid line number (%s)" % arg |
---|
891 | n/a | else: |
---|
892 | n/a | bplist = self.get_breaks(filename, lineno) |
---|
893 | n/a | err = self.clear_break(filename, lineno) |
---|
894 | n/a | if err: |
---|
895 | n/a | self.error(err) |
---|
896 | n/a | else: |
---|
897 | n/a | for bp in bplist: |
---|
898 | n/a | self.message('Deleted %s' % bp) |
---|
899 | n/a | return |
---|
900 | n/a | numberlist = arg.split() |
---|
901 | n/a | for i in numberlist: |
---|
902 | n/a | try: |
---|
903 | n/a | bp = self.get_bpbynumber(i) |
---|
904 | n/a | except ValueError as err: |
---|
905 | n/a | self.error(err) |
---|
906 | n/a | else: |
---|
907 | n/a | self.clear_bpbynumber(i) |
---|
908 | n/a | self.message('Deleted %s' % bp) |
---|
909 | n/a | do_cl = do_clear # 'c' is already an abbreviation for 'continue' |
---|
910 | n/a | |
---|
911 | n/a | complete_clear = _complete_location |
---|
912 | n/a | complete_cl = _complete_location |
---|
913 | n/a | |
---|
914 | n/a | def do_where(self, arg): |
---|
915 | n/a | """w(here) |
---|
916 | n/a | Print a stack trace, with the most recent frame at the bottom. |
---|
917 | n/a | An arrow indicates the "current frame", which determines the |
---|
918 | n/a | context of most commands. 'bt' is an alias for this command. |
---|
919 | n/a | """ |
---|
920 | n/a | self.print_stack_trace() |
---|
921 | n/a | do_w = do_where |
---|
922 | n/a | do_bt = do_where |
---|
923 | n/a | |
---|
924 | n/a | def _select_frame(self, number): |
---|
925 | n/a | assert 0 <= number < len(self.stack) |
---|
926 | n/a | self.curindex = number |
---|
927 | n/a | self.curframe = self.stack[self.curindex][0] |
---|
928 | n/a | self.curframe_locals = self.curframe.f_locals |
---|
929 | n/a | self.print_stack_entry(self.stack[self.curindex]) |
---|
930 | n/a | self.lineno = None |
---|
931 | n/a | |
---|
932 | n/a | def do_up(self, arg): |
---|
933 | n/a | """u(p) [count] |
---|
934 | n/a | Move the current frame count (default one) levels up in the |
---|
935 | n/a | stack trace (to an older frame). |
---|
936 | n/a | """ |
---|
937 | n/a | if self.curindex == 0: |
---|
938 | n/a | self.error('Oldest frame') |
---|
939 | n/a | return |
---|
940 | n/a | try: |
---|
941 | n/a | count = int(arg or 1) |
---|
942 | n/a | except ValueError: |
---|
943 | n/a | self.error('Invalid frame count (%s)' % arg) |
---|
944 | n/a | return |
---|
945 | n/a | if count < 0: |
---|
946 | n/a | newframe = 0 |
---|
947 | n/a | else: |
---|
948 | n/a | newframe = max(0, self.curindex - count) |
---|
949 | n/a | self._select_frame(newframe) |
---|
950 | n/a | do_u = do_up |
---|
951 | n/a | |
---|
952 | n/a | def do_down(self, arg): |
---|
953 | n/a | """d(own) [count] |
---|
954 | n/a | Move the current frame count (default one) levels down in the |
---|
955 | n/a | stack trace (to a newer frame). |
---|
956 | n/a | """ |
---|
957 | n/a | if self.curindex + 1 == len(self.stack): |
---|
958 | n/a | self.error('Newest frame') |
---|
959 | n/a | return |
---|
960 | n/a | try: |
---|
961 | n/a | count = int(arg or 1) |
---|
962 | n/a | except ValueError: |
---|
963 | n/a | self.error('Invalid frame count (%s)' % arg) |
---|
964 | n/a | return |
---|
965 | n/a | if count < 0: |
---|
966 | n/a | newframe = len(self.stack) - 1 |
---|
967 | n/a | else: |
---|
968 | n/a | newframe = min(len(self.stack) - 1, self.curindex + count) |
---|
969 | n/a | self._select_frame(newframe) |
---|
970 | n/a | do_d = do_down |
---|
971 | n/a | |
---|
972 | n/a | def do_until(self, arg): |
---|
973 | n/a | """unt(il) [lineno] |
---|
974 | n/a | Without argument, continue execution until the line with a |
---|
975 | n/a | number greater than the current one is reached. With a line |
---|
976 | n/a | number, continue execution until a line with a number greater |
---|
977 | n/a | or equal to that is reached. In both cases, also stop when |
---|
978 | n/a | the current frame returns. |
---|
979 | n/a | """ |
---|
980 | n/a | if arg: |
---|
981 | n/a | try: |
---|
982 | n/a | lineno = int(arg) |
---|
983 | n/a | except ValueError: |
---|
984 | n/a | self.error('Error in argument: %r' % arg) |
---|
985 | n/a | return |
---|
986 | n/a | if lineno <= self.curframe.f_lineno: |
---|
987 | n/a | self.error('"until" line number is smaller than current ' |
---|
988 | n/a | 'line number') |
---|
989 | n/a | return |
---|
990 | n/a | else: |
---|
991 | n/a | lineno = None |
---|
992 | n/a | self.set_until(self.curframe, lineno) |
---|
993 | n/a | return 1 |
---|
994 | n/a | do_unt = do_until |
---|
995 | n/a | |
---|
996 | n/a | def do_step(self, arg): |
---|
997 | n/a | """s(tep) |
---|
998 | n/a | Execute the current line, stop at the first possible occasion |
---|
999 | n/a | (either in a function that is called or in the current |
---|
1000 | n/a | function). |
---|
1001 | n/a | """ |
---|
1002 | n/a | self.set_step() |
---|
1003 | n/a | return 1 |
---|
1004 | n/a | do_s = do_step |
---|
1005 | n/a | |
---|
1006 | n/a | def do_next(self, arg): |
---|
1007 | n/a | """n(ext) |
---|
1008 | n/a | Continue execution until the next line in the current function |
---|
1009 | n/a | is reached or it returns. |
---|
1010 | n/a | """ |
---|
1011 | n/a | self.set_next(self.curframe) |
---|
1012 | n/a | return 1 |
---|
1013 | n/a | do_n = do_next |
---|
1014 | n/a | |
---|
1015 | n/a | def do_run(self, arg): |
---|
1016 | n/a | """run [args...] |
---|
1017 | n/a | Restart the debugged python program. If a string is supplied |
---|
1018 | n/a | it is split with "shlex", and the result is used as the new |
---|
1019 | n/a | sys.argv. History, breakpoints, actions and debugger options |
---|
1020 | n/a | are preserved. "restart" is an alias for "run". |
---|
1021 | n/a | """ |
---|
1022 | n/a | if arg: |
---|
1023 | n/a | import shlex |
---|
1024 | n/a | argv0 = sys.argv[0:1] |
---|
1025 | n/a | sys.argv = shlex.split(arg) |
---|
1026 | n/a | sys.argv[:0] = argv0 |
---|
1027 | n/a | # this is caught in the main debugger loop |
---|
1028 | n/a | raise Restart |
---|
1029 | n/a | |
---|
1030 | n/a | do_restart = do_run |
---|
1031 | n/a | |
---|
1032 | n/a | def do_return(self, arg): |
---|
1033 | n/a | """r(eturn) |
---|
1034 | n/a | Continue execution until the current function returns. |
---|
1035 | n/a | """ |
---|
1036 | n/a | self.set_return(self.curframe) |
---|
1037 | n/a | return 1 |
---|
1038 | n/a | do_r = do_return |
---|
1039 | n/a | |
---|
1040 | n/a | def do_continue(self, arg): |
---|
1041 | n/a | """c(ont(inue)) |
---|
1042 | n/a | Continue execution, only stop when a breakpoint is encountered. |
---|
1043 | n/a | """ |
---|
1044 | n/a | if not self.nosigint: |
---|
1045 | n/a | try: |
---|
1046 | n/a | Pdb._previous_sigint_handler = \ |
---|
1047 | n/a | signal.signal(signal.SIGINT, self.sigint_handler) |
---|
1048 | n/a | except ValueError: |
---|
1049 | n/a | # ValueError happens when do_continue() is invoked from |
---|
1050 | n/a | # a non-main thread in which case we just continue without |
---|
1051 | n/a | # SIGINT set. Would printing a message here (once) make |
---|
1052 | n/a | # sense? |
---|
1053 | n/a | pass |
---|
1054 | n/a | self.set_continue() |
---|
1055 | n/a | return 1 |
---|
1056 | n/a | do_c = do_cont = do_continue |
---|
1057 | n/a | |
---|
1058 | n/a | def do_jump(self, arg): |
---|
1059 | n/a | """j(ump) lineno |
---|
1060 | n/a | Set the next line that will be executed. Only available in |
---|
1061 | n/a | the bottom-most frame. This lets you jump back and execute |
---|
1062 | n/a | code again, or jump forward to skip code that you don't want |
---|
1063 | n/a | to run. |
---|
1064 | n/a | |
---|
1065 | n/a | It should be noted that not all jumps are allowed -- for |
---|
1066 | n/a | instance it is not possible to jump into the middle of a |
---|
1067 | n/a | for loop or out of a finally clause. |
---|
1068 | n/a | """ |
---|
1069 | n/a | if self.curindex + 1 != len(self.stack): |
---|
1070 | n/a | self.error('You can only jump within the bottom frame') |
---|
1071 | n/a | return |
---|
1072 | n/a | try: |
---|
1073 | n/a | arg = int(arg) |
---|
1074 | n/a | except ValueError: |
---|
1075 | n/a | self.error("The 'jump' command requires a line number") |
---|
1076 | n/a | else: |
---|
1077 | n/a | try: |
---|
1078 | n/a | # Do the jump, fix up our copy of the stack, and display the |
---|
1079 | n/a | # new position |
---|
1080 | n/a | self.curframe.f_lineno = arg |
---|
1081 | n/a | self.stack[self.curindex] = self.stack[self.curindex][0], arg |
---|
1082 | n/a | self.print_stack_entry(self.stack[self.curindex]) |
---|
1083 | n/a | except ValueError as e: |
---|
1084 | n/a | self.error('Jump failed: %s' % e) |
---|
1085 | n/a | do_j = do_jump |
---|
1086 | n/a | |
---|
1087 | n/a | def do_debug(self, arg): |
---|
1088 | n/a | """debug code |
---|
1089 | n/a | Enter a recursive debugger that steps through the code |
---|
1090 | n/a | argument (which is an arbitrary expression or statement to be |
---|
1091 | n/a | executed in the current environment). |
---|
1092 | n/a | """ |
---|
1093 | n/a | sys.settrace(None) |
---|
1094 | n/a | globals = self.curframe.f_globals |
---|
1095 | n/a | locals = self.curframe_locals |
---|
1096 | n/a | p = Pdb(self.completekey, self.stdin, self.stdout) |
---|
1097 | n/a | p.prompt = "(%s) " % self.prompt.strip() |
---|
1098 | n/a | self.message("ENTERING RECURSIVE DEBUGGER") |
---|
1099 | n/a | sys.call_tracing(p.run, (arg, globals, locals)) |
---|
1100 | n/a | self.message("LEAVING RECURSIVE DEBUGGER") |
---|
1101 | n/a | sys.settrace(self.trace_dispatch) |
---|
1102 | n/a | self.lastcmd = p.lastcmd |
---|
1103 | n/a | |
---|
1104 | n/a | complete_debug = _complete_expression |
---|
1105 | n/a | |
---|
1106 | n/a | def do_quit(self, arg): |
---|
1107 | n/a | """q(uit)\nexit |
---|
1108 | n/a | Quit from the debugger. The program being executed is aborted. |
---|
1109 | n/a | """ |
---|
1110 | n/a | self._user_requested_quit = True |
---|
1111 | n/a | self.set_quit() |
---|
1112 | n/a | return 1 |
---|
1113 | n/a | |
---|
1114 | n/a | do_q = do_quit |
---|
1115 | n/a | do_exit = do_quit |
---|
1116 | n/a | |
---|
1117 | n/a | def do_EOF(self, arg): |
---|
1118 | n/a | """EOF |
---|
1119 | n/a | Handles the receipt of EOF as a command. |
---|
1120 | n/a | """ |
---|
1121 | n/a | self.message('') |
---|
1122 | n/a | self._user_requested_quit = True |
---|
1123 | n/a | self.set_quit() |
---|
1124 | n/a | return 1 |
---|
1125 | n/a | |
---|
1126 | n/a | def do_args(self, arg): |
---|
1127 | n/a | """a(rgs) |
---|
1128 | n/a | Print the argument list of the current function. |
---|
1129 | n/a | """ |
---|
1130 | n/a | co = self.curframe.f_code |
---|
1131 | n/a | dict = self.curframe_locals |
---|
1132 | n/a | n = co.co_argcount |
---|
1133 | n/a | if co.co_flags & 4: n = n+1 |
---|
1134 | n/a | if co.co_flags & 8: n = n+1 |
---|
1135 | n/a | for i in range(n): |
---|
1136 | n/a | name = co.co_varnames[i] |
---|
1137 | n/a | if name in dict: |
---|
1138 | n/a | self.message('%s = %r' % (name, dict[name])) |
---|
1139 | n/a | else: |
---|
1140 | n/a | self.message('%s = *** undefined ***' % (name,)) |
---|
1141 | n/a | do_a = do_args |
---|
1142 | n/a | |
---|
1143 | n/a | def do_retval(self, arg): |
---|
1144 | n/a | """retval |
---|
1145 | n/a | Print the return value for the last return of a function. |
---|
1146 | n/a | """ |
---|
1147 | n/a | if '__return__' in self.curframe_locals: |
---|
1148 | n/a | self.message(repr(self.curframe_locals['__return__'])) |
---|
1149 | n/a | else: |
---|
1150 | n/a | self.error('Not yet returned!') |
---|
1151 | n/a | do_rv = do_retval |
---|
1152 | n/a | |
---|
1153 | n/a | def _getval(self, arg): |
---|
1154 | n/a | try: |
---|
1155 | n/a | return eval(arg, self.curframe.f_globals, self.curframe_locals) |
---|
1156 | n/a | except: |
---|
1157 | n/a | exc_info = sys.exc_info()[:2] |
---|
1158 | n/a | self.error(traceback.format_exception_only(*exc_info)[-1].strip()) |
---|
1159 | n/a | raise |
---|
1160 | n/a | |
---|
1161 | n/a | def _getval_except(self, arg, frame=None): |
---|
1162 | n/a | try: |
---|
1163 | n/a | if frame is None: |
---|
1164 | n/a | return eval(arg, self.curframe.f_globals, self.curframe_locals) |
---|
1165 | n/a | else: |
---|
1166 | n/a | return eval(arg, frame.f_globals, frame.f_locals) |
---|
1167 | n/a | except: |
---|
1168 | n/a | exc_info = sys.exc_info()[:2] |
---|
1169 | n/a | err = traceback.format_exception_only(*exc_info)[-1].strip() |
---|
1170 | n/a | return _rstr('** raised %s **' % err) |
---|
1171 | n/a | |
---|
1172 | n/a | def do_p(self, arg): |
---|
1173 | n/a | """p expression |
---|
1174 | n/a | Print the value of the expression. |
---|
1175 | n/a | """ |
---|
1176 | n/a | try: |
---|
1177 | n/a | self.message(repr(self._getval(arg))) |
---|
1178 | n/a | except: |
---|
1179 | n/a | pass |
---|
1180 | n/a | |
---|
1181 | n/a | def do_pp(self, arg): |
---|
1182 | n/a | """pp expression |
---|
1183 | n/a | Pretty-print the value of the expression. |
---|
1184 | n/a | """ |
---|
1185 | n/a | try: |
---|
1186 | n/a | self.message(pprint.pformat(self._getval(arg))) |
---|
1187 | n/a | except: |
---|
1188 | n/a | pass |
---|
1189 | n/a | |
---|
1190 | n/a | complete_print = _complete_expression |
---|
1191 | n/a | complete_p = _complete_expression |
---|
1192 | n/a | complete_pp = _complete_expression |
---|
1193 | n/a | |
---|
1194 | n/a | def do_list(self, arg): |
---|
1195 | n/a | """l(ist) [first [,last] | .] |
---|
1196 | n/a | |
---|
1197 | n/a | List source code for the current file. Without arguments, |
---|
1198 | n/a | list 11 lines around the current line or continue the previous |
---|
1199 | n/a | listing. With . as argument, list 11 lines around the current |
---|
1200 | n/a | line. With one argument, list 11 lines starting at that line. |
---|
1201 | n/a | With two arguments, list the given range; if the second |
---|
1202 | n/a | argument is less than the first, it is a count. |
---|
1203 | n/a | |
---|
1204 | n/a | The current line in the current frame is indicated by "->". |
---|
1205 | n/a | If an exception is being debugged, the line where the |
---|
1206 | n/a | exception was originally raised or propagated is indicated by |
---|
1207 | n/a | ">>", if it differs from the current line. |
---|
1208 | n/a | """ |
---|
1209 | n/a | self.lastcmd = 'list' |
---|
1210 | n/a | last = None |
---|
1211 | n/a | if arg and arg != '.': |
---|
1212 | n/a | try: |
---|
1213 | n/a | if ',' in arg: |
---|
1214 | n/a | first, last = arg.split(',') |
---|
1215 | n/a | first = int(first.strip()) |
---|
1216 | n/a | last = int(last.strip()) |
---|
1217 | n/a | if last < first: |
---|
1218 | n/a | # assume it's a count |
---|
1219 | n/a | last = first + last |
---|
1220 | n/a | else: |
---|
1221 | n/a | first = int(arg.strip()) |
---|
1222 | n/a | first = max(1, first - 5) |
---|
1223 | n/a | except ValueError: |
---|
1224 | n/a | self.error('Error in argument: %r' % arg) |
---|
1225 | n/a | return |
---|
1226 | n/a | elif self.lineno is None or arg == '.': |
---|
1227 | n/a | first = max(1, self.curframe.f_lineno - 5) |
---|
1228 | n/a | else: |
---|
1229 | n/a | first = self.lineno + 1 |
---|
1230 | n/a | if last is None: |
---|
1231 | n/a | last = first + 10 |
---|
1232 | n/a | filename = self.curframe.f_code.co_filename |
---|
1233 | n/a | breaklist = self.get_file_breaks(filename) |
---|
1234 | n/a | try: |
---|
1235 | n/a | lines = linecache.getlines(filename, self.curframe.f_globals) |
---|
1236 | n/a | self._print_lines(lines[first-1:last], first, breaklist, |
---|
1237 | n/a | self.curframe) |
---|
1238 | n/a | self.lineno = min(last, len(lines)) |
---|
1239 | n/a | if len(lines) < last: |
---|
1240 | n/a | self.message('[EOF]') |
---|
1241 | n/a | except KeyboardInterrupt: |
---|
1242 | n/a | pass |
---|
1243 | n/a | do_l = do_list |
---|
1244 | n/a | |
---|
1245 | n/a | def do_longlist(self, arg): |
---|
1246 | n/a | """longlist | ll |
---|
1247 | n/a | List the whole source code for the current function or frame. |
---|
1248 | n/a | """ |
---|
1249 | n/a | filename = self.curframe.f_code.co_filename |
---|
1250 | n/a | breaklist = self.get_file_breaks(filename) |
---|
1251 | n/a | try: |
---|
1252 | n/a | lines, lineno = getsourcelines(self.curframe) |
---|
1253 | n/a | except OSError as err: |
---|
1254 | n/a | self.error(err) |
---|
1255 | n/a | return |
---|
1256 | n/a | self._print_lines(lines, lineno, breaklist, self.curframe) |
---|
1257 | n/a | do_ll = do_longlist |
---|
1258 | n/a | |
---|
1259 | n/a | def do_source(self, arg): |
---|
1260 | n/a | """source expression |
---|
1261 | n/a | Try to get source code for the given object and display it. |
---|
1262 | n/a | """ |
---|
1263 | n/a | try: |
---|
1264 | n/a | obj = self._getval(arg) |
---|
1265 | n/a | except: |
---|
1266 | n/a | return |
---|
1267 | n/a | try: |
---|
1268 | n/a | lines, lineno = getsourcelines(obj) |
---|
1269 | n/a | except (OSError, TypeError) as err: |
---|
1270 | n/a | self.error(err) |
---|
1271 | n/a | return |
---|
1272 | n/a | self._print_lines(lines, lineno) |
---|
1273 | n/a | |
---|
1274 | n/a | complete_source = _complete_expression |
---|
1275 | n/a | |
---|
1276 | n/a | def _print_lines(self, lines, start, breaks=(), frame=None): |
---|
1277 | n/a | """Print a range of lines.""" |
---|
1278 | n/a | if frame: |
---|
1279 | n/a | current_lineno = frame.f_lineno |
---|
1280 | n/a | exc_lineno = self.tb_lineno.get(frame, -1) |
---|
1281 | n/a | else: |
---|
1282 | n/a | current_lineno = exc_lineno = -1 |
---|
1283 | n/a | for lineno, line in enumerate(lines, start): |
---|
1284 | n/a | s = str(lineno).rjust(3) |
---|
1285 | n/a | if len(s) < 4: |
---|
1286 | n/a | s += ' ' |
---|
1287 | n/a | if lineno in breaks: |
---|
1288 | n/a | s += 'B' |
---|
1289 | n/a | else: |
---|
1290 | n/a | s += ' ' |
---|
1291 | n/a | if lineno == current_lineno: |
---|
1292 | n/a | s += '->' |
---|
1293 | n/a | elif lineno == exc_lineno: |
---|
1294 | n/a | s += '>>' |
---|
1295 | n/a | self.message(s + '\t' + line.rstrip()) |
---|
1296 | n/a | |
---|
1297 | n/a | def do_whatis(self, arg): |
---|
1298 | n/a | """whatis arg |
---|
1299 | n/a | Print the type of the argument. |
---|
1300 | n/a | """ |
---|
1301 | n/a | try: |
---|
1302 | n/a | value = self._getval(arg) |
---|
1303 | n/a | except: |
---|
1304 | n/a | # _getval() already printed the error |
---|
1305 | n/a | return |
---|
1306 | n/a | code = None |
---|
1307 | n/a | # Is it a function? |
---|
1308 | n/a | try: |
---|
1309 | n/a | code = value.__code__ |
---|
1310 | n/a | except Exception: |
---|
1311 | n/a | pass |
---|
1312 | n/a | if code: |
---|
1313 | n/a | self.message('Function %s' % code.co_name) |
---|
1314 | n/a | return |
---|
1315 | n/a | # Is it an instance method? |
---|
1316 | n/a | try: |
---|
1317 | n/a | code = value.__func__.__code__ |
---|
1318 | n/a | except Exception: |
---|
1319 | n/a | pass |
---|
1320 | n/a | if code: |
---|
1321 | n/a | self.message('Method %s' % code.co_name) |
---|
1322 | n/a | return |
---|
1323 | n/a | # Is it a class? |
---|
1324 | n/a | if value.__class__ is type: |
---|
1325 | n/a | self.message('Class %s.%s' % (value.__module__, value.__qualname__)) |
---|
1326 | n/a | return |
---|
1327 | n/a | # None of the above... |
---|
1328 | n/a | self.message(type(value)) |
---|
1329 | n/a | |
---|
1330 | n/a | complete_whatis = _complete_expression |
---|
1331 | n/a | |
---|
1332 | n/a | def do_display(self, arg): |
---|
1333 | n/a | """display [expression] |
---|
1334 | n/a | |
---|
1335 | n/a | Display the value of the expression if it changed, each time execution |
---|
1336 | n/a | stops in the current frame. |
---|
1337 | n/a | |
---|
1338 | n/a | Without expression, list all display expressions for the current frame. |
---|
1339 | n/a | """ |
---|
1340 | n/a | if not arg: |
---|
1341 | n/a | self.message('Currently displaying:') |
---|
1342 | n/a | for item in self.displaying.get(self.curframe, {}).items(): |
---|
1343 | n/a | self.message('%s: %r' % item) |
---|
1344 | n/a | else: |
---|
1345 | n/a | val = self._getval_except(arg) |
---|
1346 | n/a | self.displaying.setdefault(self.curframe, {})[arg] = val |
---|
1347 | n/a | self.message('display %s: %r' % (arg, val)) |
---|
1348 | n/a | |
---|
1349 | n/a | complete_display = _complete_expression |
---|
1350 | n/a | |
---|
1351 | n/a | def do_undisplay(self, arg): |
---|
1352 | n/a | """undisplay [expression] |
---|
1353 | n/a | |
---|
1354 | n/a | Do not display the expression any more in the current frame. |
---|
1355 | n/a | |
---|
1356 | n/a | Without expression, clear all display expressions for the current frame. |
---|
1357 | n/a | """ |
---|
1358 | n/a | if arg: |
---|
1359 | n/a | try: |
---|
1360 | n/a | del self.displaying.get(self.curframe, {})[arg] |
---|
1361 | n/a | except KeyError: |
---|
1362 | n/a | self.error('not displaying %s' % arg) |
---|
1363 | n/a | else: |
---|
1364 | n/a | self.displaying.pop(self.curframe, None) |
---|
1365 | n/a | |
---|
1366 | n/a | def complete_undisplay(self, text, line, begidx, endidx): |
---|
1367 | n/a | return [e for e in self.displaying.get(self.curframe, {}) |
---|
1368 | n/a | if e.startswith(text)] |
---|
1369 | n/a | |
---|
1370 | n/a | def do_interact(self, arg): |
---|
1371 | n/a | """interact |
---|
1372 | n/a | |
---|
1373 | n/a | Start an interactive interpreter whose global namespace |
---|
1374 | n/a | contains all the (global and local) names found in the current scope. |
---|
1375 | n/a | """ |
---|
1376 | n/a | ns = self.curframe.f_globals.copy() |
---|
1377 | n/a | ns.update(self.curframe_locals) |
---|
1378 | n/a | code.interact("*interactive*", local=ns) |
---|
1379 | n/a | |
---|
1380 | n/a | def do_alias(self, arg): |
---|
1381 | n/a | """alias [name [command [parameter parameter ...] ]] |
---|
1382 | n/a | Create an alias called 'name' that executes 'command'. The |
---|
1383 | n/a | command must *not* be enclosed in quotes. Replaceable |
---|
1384 | n/a | parameters can be indicated by %1, %2, and so on, while %* is |
---|
1385 | n/a | replaced by all the parameters. If no command is given, the |
---|
1386 | n/a | current alias for name is shown. If no name is given, all |
---|
1387 | n/a | aliases are listed. |
---|
1388 | n/a | |
---|
1389 | n/a | Aliases may be nested and can contain anything that can be |
---|
1390 | n/a | legally typed at the pdb prompt. Note! You *can* override |
---|
1391 | n/a | internal pdb commands with aliases! Those internal commands |
---|
1392 | n/a | are then hidden until the alias is removed. Aliasing is |
---|
1393 | n/a | recursively applied to the first word of the command line; all |
---|
1394 | n/a | other words in the line are left alone. |
---|
1395 | n/a | |
---|
1396 | n/a | As an example, here are two useful aliases (especially when |
---|
1397 | n/a | placed in the .pdbrc file): |
---|
1398 | n/a | |
---|
1399 | n/a | # Print instance variables (usage "pi classInst") |
---|
1400 | n/a | alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k]) |
---|
1401 | n/a | # Print instance variables in self |
---|
1402 | n/a | alias ps pi self |
---|
1403 | n/a | """ |
---|
1404 | n/a | args = arg.split() |
---|
1405 | n/a | if len(args) == 0: |
---|
1406 | n/a | keys = sorted(self.aliases.keys()) |
---|
1407 | n/a | for alias in keys: |
---|
1408 | n/a | self.message("%s = %s" % (alias, self.aliases[alias])) |
---|
1409 | n/a | return |
---|
1410 | n/a | if args[0] in self.aliases and len(args) == 1: |
---|
1411 | n/a | self.message("%s = %s" % (args[0], self.aliases[args[0]])) |
---|
1412 | n/a | else: |
---|
1413 | n/a | self.aliases[args[0]] = ' '.join(args[1:]) |
---|
1414 | n/a | |
---|
1415 | n/a | def do_unalias(self, arg): |
---|
1416 | n/a | """unalias name |
---|
1417 | n/a | Delete the specified alias. |
---|
1418 | n/a | """ |
---|
1419 | n/a | args = arg.split() |
---|
1420 | n/a | if len(args) == 0: return |
---|
1421 | n/a | if args[0] in self.aliases: |
---|
1422 | n/a | del self.aliases[args[0]] |
---|
1423 | n/a | |
---|
1424 | n/a | def complete_unalias(self, text, line, begidx, endidx): |
---|
1425 | n/a | return [a for a in self.aliases if a.startswith(text)] |
---|
1426 | n/a | |
---|
1427 | n/a | # List of all the commands making the program resume execution. |
---|
1428 | n/a | commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return', |
---|
1429 | n/a | 'do_quit', 'do_jump'] |
---|
1430 | n/a | |
---|
1431 | n/a | # Print a traceback starting at the top stack frame. |
---|
1432 | n/a | # The most recently entered frame is printed last; |
---|
1433 | n/a | # this is different from dbx and gdb, but consistent with |
---|
1434 | n/a | # the Python interpreter's stack trace. |
---|
1435 | n/a | # It is also consistent with the up/down commands (which are |
---|
1436 | n/a | # compatible with dbx and gdb: up moves towards 'main()' |
---|
1437 | n/a | # and down moves towards the most recent stack frame). |
---|
1438 | n/a | |
---|
1439 | n/a | def print_stack_trace(self): |
---|
1440 | n/a | try: |
---|
1441 | n/a | for frame_lineno in self.stack: |
---|
1442 | n/a | self.print_stack_entry(frame_lineno) |
---|
1443 | n/a | except KeyboardInterrupt: |
---|
1444 | n/a | pass |
---|
1445 | n/a | |
---|
1446 | n/a | def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix): |
---|
1447 | n/a | frame, lineno = frame_lineno |
---|
1448 | n/a | if frame is self.curframe: |
---|
1449 | n/a | prefix = '> ' |
---|
1450 | n/a | else: |
---|
1451 | n/a | prefix = ' ' |
---|
1452 | n/a | self.message(prefix + |
---|
1453 | n/a | self.format_stack_entry(frame_lineno, prompt_prefix)) |
---|
1454 | n/a | |
---|
1455 | n/a | # Provide help |
---|
1456 | n/a | |
---|
1457 | n/a | def do_help(self, arg): |
---|
1458 | n/a | """h(elp) |
---|
1459 | n/a | Without argument, print the list of available commands. |
---|
1460 | n/a | With a command name as argument, print help about that command. |
---|
1461 | n/a | "help pdb" shows the full pdb documentation. |
---|
1462 | n/a | "help exec" gives help on the ! command. |
---|
1463 | n/a | """ |
---|
1464 | n/a | if not arg: |
---|
1465 | n/a | return cmd.Cmd.do_help(self, arg) |
---|
1466 | n/a | try: |
---|
1467 | n/a | try: |
---|
1468 | n/a | topic = getattr(self, 'help_' + arg) |
---|
1469 | n/a | return topic() |
---|
1470 | n/a | except AttributeError: |
---|
1471 | n/a | command = getattr(self, 'do_' + arg) |
---|
1472 | n/a | except AttributeError: |
---|
1473 | n/a | self.error('No help for %r' % arg) |
---|
1474 | n/a | else: |
---|
1475 | n/a | if sys.flags.optimize >= 2: |
---|
1476 | n/a | self.error('No help for %r; please do not run Python with -OO ' |
---|
1477 | n/a | 'if you need command help' % arg) |
---|
1478 | n/a | return |
---|
1479 | n/a | self.message(command.__doc__.rstrip()) |
---|
1480 | n/a | |
---|
1481 | n/a | do_h = do_help |
---|
1482 | n/a | |
---|
1483 | n/a | def help_exec(self): |
---|
1484 | n/a | """(!) statement |
---|
1485 | n/a | Execute the (one-line) statement in the context of the current |
---|
1486 | n/a | stack frame. The exclamation point can be omitted unless the |
---|
1487 | n/a | first word of the statement resembles a debugger command. To |
---|
1488 | n/a | assign to a global variable you must always prefix the command |
---|
1489 | n/a | with a 'global' command, e.g.: |
---|
1490 | n/a | (Pdb) global list_options; list_options = ['-l'] |
---|
1491 | n/a | (Pdb) |
---|
1492 | n/a | """ |
---|
1493 | n/a | self.message((self.help_exec.__doc__ or '').strip()) |
---|
1494 | n/a | |
---|
1495 | n/a | def help_pdb(self): |
---|
1496 | n/a | help() |
---|
1497 | n/a | |
---|
1498 | n/a | # other helper functions |
---|
1499 | n/a | |
---|
1500 | n/a | def lookupmodule(self, filename): |
---|
1501 | n/a | """Helper function for break/clear parsing -- may be overridden. |
---|
1502 | n/a | |
---|
1503 | n/a | lookupmodule() translates (possibly incomplete) file or module name |
---|
1504 | n/a | into an absolute file name. |
---|
1505 | n/a | """ |
---|
1506 | n/a | if os.path.isabs(filename) and os.path.exists(filename): |
---|
1507 | n/a | return filename |
---|
1508 | n/a | f = os.path.join(sys.path[0], filename) |
---|
1509 | n/a | if os.path.exists(f) and self.canonic(f) == self.mainpyfile: |
---|
1510 | n/a | return f |
---|
1511 | n/a | root, ext = os.path.splitext(filename) |
---|
1512 | n/a | if ext == '': |
---|
1513 | n/a | filename = filename + '.py' |
---|
1514 | n/a | if os.path.isabs(filename): |
---|
1515 | n/a | return filename |
---|
1516 | n/a | for dirname in sys.path: |
---|
1517 | n/a | while os.path.islink(dirname): |
---|
1518 | n/a | dirname = os.readlink(dirname) |
---|
1519 | n/a | fullname = os.path.join(dirname, filename) |
---|
1520 | n/a | if os.path.exists(fullname): |
---|
1521 | n/a | return fullname |
---|
1522 | n/a | return None |
---|
1523 | n/a | |
---|
1524 | n/a | def _runscript(self, filename): |
---|
1525 | n/a | # The script has to run in __main__ namespace (or imports from |
---|
1526 | n/a | # __main__ will break). |
---|
1527 | n/a | # |
---|
1528 | n/a | # So we clear up the __main__ and set several special variables |
---|
1529 | n/a | # (this gets rid of pdb's globals and cleans old variables on restarts). |
---|
1530 | n/a | import __main__ |
---|
1531 | n/a | __main__.__dict__.clear() |
---|
1532 | n/a | __main__.__dict__.update({"__name__" : "__main__", |
---|
1533 | n/a | "__file__" : filename, |
---|
1534 | n/a | "__builtins__": __builtins__, |
---|
1535 | n/a | }) |
---|
1536 | n/a | |
---|
1537 | n/a | # When bdb sets tracing, a number of call and line events happens |
---|
1538 | n/a | # BEFORE debugger even reaches user's code (and the exact sequence of |
---|
1539 | n/a | # events depends on python version). So we take special measures to |
---|
1540 | n/a | # avoid stopping before we reach the main script (see user_line and |
---|
1541 | n/a | # user_call for details). |
---|
1542 | n/a | self._wait_for_mainpyfile = True |
---|
1543 | n/a | self.mainpyfile = self.canonic(filename) |
---|
1544 | n/a | self._user_requested_quit = False |
---|
1545 | n/a | with open(filename, "rb") as fp: |
---|
1546 | n/a | statement = "exec(compile(%r, %r, 'exec'))" % \ |
---|
1547 | n/a | (fp.read(), self.mainpyfile) |
---|
1548 | n/a | self.run(statement) |
---|
1549 | n/a | |
---|
1550 | n/a | # Collect all command help into docstring, if not run with -OO |
---|
1551 | n/a | |
---|
1552 | n/a | if __doc__ is not None: |
---|
1553 | n/a | # unfortunately we can't guess this order from the class definition |
---|
1554 | n/a | _help_order = [ |
---|
1555 | n/a | 'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable', |
---|
1556 | n/a | 'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until', |
---|
1557 | n/a | 'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist', |
---|
1558 | n/a | 'args', 'p', 'pp', 'whatis', 'source', 'display', 'undisplay', |
---|
1559 | n/a | 'interact', 'alias', 'unalias', 'debug', 'quit', |
---|
1560 | n/a | ] |
---|
1561 | n/a | |
---|
1562 | n/a | for _command in _help_order: |
---|
1563 | n/a | __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n' |
---|
1564 | n/a | __doc__ += Pdb.help_exec.__doc__ |
---|
1565 | n/a | |
---|
1566 | n/a | del _help_order, _command |
---|
1567 | n/a | |
---|
1568 | n/a | |
---|
1569 | n/a | # Simplified interface |
---|
1570 | n/a | |
---|
1571 | n/a | def run(statement, globals=None, locals=None): |
---|
1572 | n/a | Pdb().run(statement, globals, locals) |
---|
1573 | n/a | |
---|
1574 | n/a | def runeval(expression, globals=None, locals=None): |
---|
1575 | n/a | return Pdb().runeval(expression, globals, locals) |
---|
1576 | n/a | |
---|
1577 | n/a | def runctx(statement, globals, locals): |
---|
1578 | n/a | # B/W compatibility |
---|
1579 | n/a | run(statement, globals, locals) |
---|
1580 | n/a | |
---|
1581 | n/a | def runcall(*args, **kwds): |
---|
1582 | n/a | return Pdb().runcall(*args, **kwds) |
---|
1583 | n/a | |
---|
1584 | n/a | def set_trace(): |
---|
1585 | n/a | Pdb().set_trace(sys._getframe().f_back) |
---|
1586 | n/a | |
---|
1587 | n/a | # Post-Mortem interface |
---|
1588 | n/a | |
---|
1589 | n/a | def post_mortem(t=None): |
---|
1590 | n/a | # handling the default |
---|
1591 | n/a | if t is None: |
---|
1592 | n/a | # sys.exc_info() returns (type, value, traceback) if an exception is |
---|
1593 | n/a | # being handled, otherwise it returns None |
---|
1594 | n/a | t = sys.exc_info()[2] |
---|
1595 | n/a | if t is None: |
---|
1596 | n/a | raise ValueError("A valid traceback must be passed if no " |
---|
1597 | n/a | "exception is being handled") |
---|
1598 | n/a | |
---|
1599 | n/a | p = Pdb() |
---|
1600 | n/a | p.reset() |
---|
1601 | n/a | p.interaction(None, t) |
---|
1602 | n/a | |
---|
1603 | n/a | def pm(): |
---|
1604 | n/a | post_mortem(sys.last_traceback) |
---|
1605 | n/a | |
---|
1606 | n/a | |
---|
1607 | n/a | # Main program for testing |
---|
1608 | n/a | |
---|
1609 | n/a | TESTCMD = 'import x; x.main()' |
---|
1610 | n/a | |
---|
1611 | n/a | def test(): |
---|
1612 | n/a | run(TESTCMD) |
---|
1613 | n/a | |
---|
1614 | n/a | # print help |
---|
1615 | n/a | def help(): |
---|
1616 | n/a | import pydoc |
---|
1617 | n/a | pydoc.pager(__doc__) |
---|
1618 | n/a | |
---|
1619 | n/a | _usage = """\ |
---|
1620 | n/a | usage: pdb.py [-c command] ... pyfile [arg] ... |
---|
1621 | n/a | |
---|
1622 | n/a | Debug the Python program given by pyfile. |
---|
1623 | n/a | |
---|
1624 | n/a | Initial commands are read from .pdbrc files in your home directory |
---|
1625 | n/a | and in the current directory, if they exist. Commands supplied with |
---|
1626 | n/a | -c are executed after commands from .pdbrc files. |
---|
1627 | n/a | |
---|
1628 | n/a | To let the script run until an exception occurs, use "-c continue". |
---|
1629 | n/a | To let the script run up to a given line X in the debugged file, use |
---|
1630 | n/a | "-c 'until X'".""" |
---|
1631 | n/a | |
---|
1632 | n/a | def main(): |
---|
1633 | n/a | import getopt |
---|
1634 | n/a | |
---|
1635 | n/a | opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['--help', '--command=']) |
---|
1636 | n/a | |
---|
1637 | n/a | if not args: |
---|
1638 | n/a | print(_usage) |
---|
1639 | n/a | sys.exit(2) |
---|
1640 | n/a | |
---|
1641 | n/a | commands = [] |
---|
1642 | n/a | for opt, optarg in opts: |
---|
1643 | n/a | if opt in ['-h', '--help']: |
---|
1644 | n/a | print(_usage) |
---|
1645 | n/a | sys.exit() |
---|
1646 | n/a | elif opt in ['-c', '--command']: |
---|
1647 | n/a | commands.append(optarg) |
---|
1648 | n/a | |
---|
1649 | n/a | mainpyfile = args[0] # Get script filename |
---|
1650 | n/a | if not os.path.exists(mainpyfile): |
---|
1651 | n/a | print('Error:', mainpyfile, 'does not exist') |
---|
1652 | n/a | sys.exit(1) |
---|
1653 | n/a | |
---|
1654 | n/a | sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list |
---|
1655 | n/a | |
---|
1656 | n/a | # Replace pdb's dir with script's dir in front of module search path. |
---|
1657 | n/a | sys.path[0] = os.path.dirname(mainpyfile) |
---|
1658 | n/a | |
---|
1659 | n/a | # Note on saving/restoring sys.argv: it's a good idea when sys.argv was |
---|
1660 | n/a | # modified by the script being debugged. It's a bad idea when it was |
---|
1661 | n/a | # changed by the user from the command line. There is a "restart" command |
---|
1662 | n/a | # which allows explicit specification of command line arguments. |
---|
1663 | n/a | pdb = Pdb() |
---|
1664 | n/a | pdb.rcLines.extend(commands) |
---|
1665 | n/a | while True: |
---|
1666 | n/a | try: |
---|
1667 | n/a | pdb._runscript(mainpyfile) |
---|
1668 | n/a | if pdb._user_requested_quit: |
---|
1669 | n/a | break |
---|
1670 | n/a | print("The program finished and will be restarted") |
---|
1671 | n/a | except Restart: |
---|
1672 | n/a | print("Restarting", mainpyfile, "with arguments:") |
---|
1673 | n/a | print("\t" + " ".join(args)) |
---|
1674 | n/a | except SystemExit: |
---|
1675 | n/a | # In most cases SystemExit does not warrant a post-mortem session. |
---|
1676 | n/a | print("The program exited via sys.exit(). Exit status:", end=' ') |
---|
1677 | n/a | print(sys.exc_info()[1]) |
---|
1678 | n/a | except SyntaxError: |
---|
1679 | n/a | traceback.print_exc() |
---|
1680 | n/a | sys.exit(1) |
---|
1681 | n/a | except: |
---|
1682 | n/a | traceback.print_exc() |
---|
1683 | n/a | print("Uncaught exception. Entering post mortem debugging") |
---|
1684 | n/a | print("Running 'cont' or 'step' will restart the program") |
---|
1685 | n/a | t = sys.exc_info()[2] |
---|
1686 | n/a | pdb.interaction(None, t) |
---|
1687 | n/a | print("Post mortem debugger finished. The " + mainpyfile + |
---|
1688 | n/a | " will be restarted") |
---|
1689 | n/a | |
---|
1690 | n/a | |
---|
1691 | n/a | # When invoked as main program, invoke the debugger on a script |
---|
1692 | n/a | if __name__ == '__main__': |
---|
1693 | n/a | import pdb |
---|
1694 | n/a | pdb.main() |
---|