Debian Codegraph @

texmf-dist/doc/latex/pythontex/syncpdb.py

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 '''
5 Synchronized Python Debugger (syncpdb)
6
7 Provides a wrapper for pdb that synchronizes code line numbers with the line
8 numbers of a document from which the code was extracted. This allows pdb to
9 be used more effectively with literate programming-type systems. The wrapper
10 was initially created to work with PythonTeX, which allows Python code
11 entered within a LaTeX document to be executed. In that case, syncpdb makes
12 possible debugging in which both the code line numbers, and the corresponding
13 line numbers in the LaTeX document, are displayed.
14
15 All pdb commands function normally. In addition, commands that take a line
16 number or filename:lineno as an argument will also take these same values
17 with a percent symbol (%) prefix. If the percent symbol is present, then
18 syncpdb interprets the filename and line number as referring to the document,
19 rather than to the code that is executed. It will translate the filename and
20 line number to the corresponding code equivalents, and then pass these to the
21 standard pdb internals. For example, the pdb command `list 50` would list
22 the code that is being executed, centered around line 50. syncpdb allows the
23 command `list %10`, which would list the code that is being executed,
24 centered around the code that came from line 10 in the main document. (If no
25 file name is given, then the main document is assumed.) If the code instead
26 came from an inputed file `input.tex`, then `list %input.tex:10` could be
27 used.
28
29 * * *
30
31 The synchronization is accomplished via a synchronization file with
32 the extension .syncdb. It should be located in the same directory as the
33 code it synchronizes, and should have the same name as the code, with the
34 addition of the .syncdb extension. For example, `code.py` would have
35 `code.py.syncdb`. Currently, the .syncdb must be encoded in UTF8. The file
36 has the following format. For each chunk of code extracted from a document
37 for execution, the file contains a line with the following information:
38 ```
39 <code filename>,<code lineno>,<doc filename>,<doc lineno>,<chunk length>
40 ```/
41 The first line of the file must be
42 ```
43 <main code filename>,,<main doc filename>,,
44 ```/
45 All code filenames should be given relative to the main code filename.
46
47 The .syncdb format is thus a comma-separated value (csv) format. The
48 elements are defined as follows:
49 * <code filename>: The name of the code file in which the current chunk
50 of user code is inserted. This should be double-quoted if it contains
51 commas.
52 * <code lineno>: The line of the executed code on which the current chunk
53 of user code begins.
54 * <doc filename>: The name of the document file from which the current
55 chunk of user code was extracted. This should be double-quoted if it
56 contains commas.
57 * <doc lineno>: The line number in the document file where the chunk of
58 user code begins.
59 * <chunk length>: The length of the chunk of code (number of lines).
60 This information is sufficient for calculating the relationship of each line
61 in the code that is executed (and that originated in the document, not a
62 template) with a line in the document from which the code was extracted.
63
64 As an example, suppose that a document main.tex contains 10 lines of Python
65 code, beginning on line 50, that are to be executed. When this code is
66 inserted into a template for execution, it begins on line 75 of the code that
67 is actually executed. In this case, the .syncdb file would contain the
68 following information for this chunk of code.
69 ```
70 code.py,75,main.tex,50,10
71 ```/
72
73 While the .syncdb format is currently only intended for simple literate
74 programming-type systems, in the future it may be extended for more complex
75 cases in which a chunk of code may be substituted into another chunk, perhaps
76 with variable replacement. In such cases, the `<doc filename>, <doc lineno>,`
77 may be repeated for each location with a connection to a given line of code,
78 allowing a complete traceback of the code's origin to be assembled. The
79 rightmost `<doc filename>, <doc lineno>,` should be the most specific of all
80 such pairs.
81
82 * * *
83
84 This code is based on pdb.py and bdb.py from the Python standard library.
85 It subclasses Pdb(), overwriting a number of methods to provide
86 synchronization between the code that is executed and the file from which it
87 was extracted. It also provides a number functions adapted from pdb.py to
88 govern execution. Most of the modifications to the pdb and bdb sources are
89 wrapped in the pair of comments `# SPdb` and `# /SPdb`.
90
91 This code is compatible with both Python 2 and Python 3. It is based on the
92 pdb.py and bdb.py from Python 2.7.5 and Python 3.3.2. Several minor
93 modifications were required to get the code from both sources to play nicely
94 within the same file.
95
96 Licensed under the BSD 3-Clause License
97
98 Copyright (c) 2014, Geoffrey M. Poore
99 '''
100
101 import sys
102 import os
103 import pdb
104 import bdb
105 import linecache
106 if sys.version_info.major == 2:
107 from io import open
108 from repr import Repr
109 else:
110 import inspect
111 import dis
112 import re
113 from collections import defaultdict, namedtuple
114 import traceback
115
116
117 __version__ = '0.2'
118
119
120 __all__ = ["run", "pm", "SyncPdb", "runeval", "runctx", "runcall", "set_trace",
121 "post_mortem", "help"]
122
123
124 if sys.version_info.major == 2:
125
126 class Restart(Exception):
127 """Causes a debugger to be restarted for the debugged python program."""
128 pass
129
130 _repr = Repr()
131 _repr.maxstring = 200
132 _saferepr = _repr.repr
133
134 def find_function(funcname, filename):
135 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
136 try:
137 fp = open(filename)
138 except IOError:
139 return None
140 # consumer of this info expects the first line to be 1
141 lineno = 1
142 answer = None
143 while 1:
144 line = fp.readline()
145 if line == '':
146 break
147 if cre.match(line):
148 answer = funcname, filename, lineno
149 break
150 lineno = lineno + 1
151 fp.close()
152 return answer
153
154 line_prefix = '\n-> '
155
156 else:
157
158 class Restart(Exception):
159 """Causes a debugger to be restarted for the debugged python program."""
160 pass
161
162 def find_function(funcname, filename):
163 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
164 try:
165 fp = open(filename)
166 except IOError:
167 return None
168 # consumer of this info expects the first line to be 1
169 lineno = 1
170 answer = None
171 while True:
172 line = fp.readline()
173 if line == '':
174 break
175 if cre.match(line):
176 answer = funcname, filename, lineno
177 break
178 lineno += 1
179 fp.close()
180 return answer
181
182 def getsourcelines(obj):
183 lines, lineno = inspect.findsource(obj)
184 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
185 # must be a module frame: do not try to cut a block out of it
186 return lines, 1
187 elif inspect.ismodule(obj):
188 return lines, 1
189 return inspect.getblock(lines[lineno:]), lineno+1
190
191 def lasti2lineno(code, lasti):
192 linestarts = list(dis.findlinestarts(code))
193 linestarts.reverse()
194 for i, lineno in linestarts:
195 if lasti >= i:
196 return lineno
197 return 0
198
199 class _rstr(str):
200 """String that doesn't quote its repr."""
201 def __repr__(self):
202 return self
203
204 line_prefix = '\n-> '
205
206
207
208 Sync = namedtuple('Sync', ['file', 'line'])
209 def defaultsync():
210 return Sync(None, None)
211
212
213 class SyncPdb(pdb.Pdb):
214 '''
215 Methods that need to be redefined from Pdb for Python 2
216 + do_list()
217 + format_stack_entry() (bdb)
218 + do_break()
219 x clear_break() (bdb)
220 + bpprint() (bdb)
221 + do_jump()
222 + do_clear()
223 + format_stack_entry() (bdb)
224
225 Methods that need to be redefined from Pdb for Python 3
226 + do_break()
227 + _print_lines()
228 x clear_break() (bdb)
229 + bpformat() (bdb)
230 + do_jump()
231 + do_list()
232 + do_long_list()
233 + do_source()
234 + format_stack_entry() (bdb)
235 + do_clear()
236 '''
237 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
238 syncdb=None):
239 pdb.Pdb.__init__(self, completekey=completekey, stdin=stdin,
240 stdout=stdout, skip=skip)
241 self._load_syncdb()
242
243 _code_to_doc_dict = defaultdict(lambda: defaultdict(defaultsync))
244 _doc_to_code_dict = defaultdict(lambda: defaultdict(defaultsync))
245
246 _syncdb_pattern = re.compile('([^"]*|"[^"]*"),(.*?),([^"]*|"[^"]*"),(.*?),(.*?)\n')
247
248 def _load_syncdb(self):
249 syncdb_fname = sys.argv[0] + '.syncdb'
250 if os.path.isfile(syncdb_fname):
251 f = open(syncdb_fname, 'r', encoding='utf8')
252 data = f.readlines()
253 f.close()
254 main_code_fname, main_doc_fname = [x.strip('"') for x in self._syncdb_pattern.match(data[0]).groups()[0:3:2]]
255 self.main_code_fname = main_code_fname
256 self.main_doc_fname = main_doc_fname
257 # If the main code file isn't being executed from its own
258 # directory, then we will need to correct all code file paths
259 # for this.
260 self.current_code_path, self.current_code_fname = os.path.split(sys.argv[0])
261 # Check to make sure syncdb is compatible. It could have been
262 # copied under another name in an attempt to reuse it with
263 # another, related script. But that doesn't work, at least
264 # currently.
265 if self.current_code_fname != self.main_code_fname:
266 sys.exit('The synchonization file is only compatible with "{0}", not "{1}"'.format(self.main_code_fname, self.current_code_fname))
267 for line in data[1:]:
268 code_fname, code_start_lineno, doc_fname, doc_start_lineno, input_length = self._syncdb_pattern.match(line).groups()
269 code_fname = os.path.normcase(code_fname.strip('"').replace('\\', '/'))
270 doc_fname = doc_fname.strip('"')
271 code_start_lineno = int(code_start_lineno)
272 doc_start_lineno = int(doc_start_lineno)
273 input_length = int(input_length)
274 code_fname_key = os.path.join(self.current_code_path, code_fname)
275 code_fname_key_full = os.path.normcase(os.path.abspath(code_fname_key))
276 is_main_code = code_fname == main_code_fname
277 is_main_doc = doc_fname == main_doc_fname
278 for n in range(0, input_length):
279 s = Sync(doc_fname, doc_start_lineno + n)
280 self._code_to_doc_dict[code_fname_key][code_start_lineno + n] = s
281 self._code_to_doc_dict[code_fname_key_full][code_start_lineno + n] = s
282 if is_main_code:
283 self._code_to_doc_dict[''][code_start_lineno + n] = s
284 # When there are multiple sources of code in a
285 # single line of the document, we want to use the
286 # first one
287 if doc_start_lineno + n not in self._doc_to_code_dict[doc_fname]:
288 s = Sync(code_fname_key, code_start_lineno + n)
289 self._doc_to_code_dict[doc_fname][doc_start_lineno + n] = s
290 if is_main_doc:
291 self._doc_to_code_dict[''][doc_start_lineno + n] = s
292 else:
293 sys.exit('Could not find synchronization file "{0}"'.format(syncdb_fname))
294
295 def code_to_doc(self, code_fname, code_lineno):
296 if code_fname in self._code_to_doc_dict:
297 if self._code_to_doc_dict[code_fname]:
298 return self._code_to_doc_dict[code_fname][code_lineno]
299 else:
300 return defaultsync()
301 else:
302 if code_fname not in self._code_to_doc_dict:
303 self._code_to_doc_dict[code_fname] = None
304 return self.code_to_doc(code_fname, code_lineno)
305
306 def doc_to_code(self, doc_fname, doc_lineno):
307 if doc_fname in self._doc_to_code_dict:
308 if self._doc_to_code_dict[doc_fname]:
309 return self._doc_to_code_dict[doc_fname][doc_lineno]
310 else:
311 return defaultsync()
312 else:
313 if doc_fname not in self._doc_to_code_dict:
314 self._doc_to_code_dict[doc_fname] = None
315 return self.doc_to_code(doc_fname, doc_lineno)
316
317 _line_numbering_offset = 5
318
319 def _format_line_main_doc(self, s, l):
320 return '{0} '.format(l).rjust(self._line_numbering_offset) + s
321
322 def _format_line_other_doc(self, s, l):
323 return '{0} '.format(l).rjust(self._line_numbering_offset) + s
324
325 def _format_line_no_doc(self, s):
326 return ' '*self._line_numbering_offset + s
327
328 _eof_template = ' '*(_line_numbering_offset-1) + '[EOF]'
329
330 _last_doc_fname = None
331
332 _doc_switch_template = ' {0}:'
333
334 _doc_command_char = '%'
335 _doc_command_char_stripset = ' {0}'.format(_doc_command_char)
336
337
338 if sys.version_info.major == 2:
339
340 def bpprint(self, bp, out=None):
341 '''
342 Replacement for Bdb.bpprint()
343 '''
344 if out is None:
345 out = sys.stdout
346 if bp.temporary:
347 disp = 'del '
348 else:
349 disp = 'keep '
350 if bp.enabled:
351 disp = disp + 'yes '
352 else:
353 disp = disp + 'no '
354 if bp.doc_file is None:
355 print >>out, '%-4dbreakpoint %s at %s:%d' % (bp.number, disp,
356 bp.file, bp.line)
357 else:
358 print >>out, '%-4dbreakpoint %s at %s:%d (%s:%d)' % (bp.number, disp,
359 bp.file, bp.line,
360 bp.doc_file, bp.doc_line)
361 if bp.cond:
362 print >>out, '\tstop only if %s' % (bp.cond,)
363 if bp.ignore:
364 print >>out, '\tignore next %d hits' % (bp.ignore)
365 if (bp.hits):
366 if (bp.hits > 1): ss = 's'
367 else: ss = ''
368 print >>out, ('\tbreakpoint already hit %d time%s' %
369 (bp.hits, ss))
370
371
372 def do_break(self, arg, temporary = 0):
373 # break [ ([filename:]lineno | function) [, "condition"] ]
374 if not arg:
375 if self.breaks: # There's at least one
376 print >>self.stdout, "Num Type Disp Enb Where"
377 for bp in bdb.Breakpoint.bpbynumber:
378 if bp:
379 # SPdb
380 self.bpprint(bp, self.stdout)
381 #bp.bpprint(self.stdout)
382 # /SPdb
383 return
384 # parse arguments; comma has lowest precedence
385 # and cannot occur in filename
386 filename = None
387 lineno = None
388 cond = None
389 comma = arg.find(',')
390 if comma > 0:
391 # parse stuff after comma: "condition"
392 cond = arg[comma+1:].lstrip()
393 arg = arg[:comma].lstrip()
394 # SPdb
395 arg = arg.strip()
396 if arg.startswith(self._doc_command_char):
397 convert = True
398 arg2 = arg.lstrip(self._doc_command_char_stripset)
399 else:
400 convert = False
401 arg2 = arg
402 # parse stuff before comma: [filename:]lineno | function
403 colon = arg2.rfind(':')
404 funcname = None
405 if colon >= 0:
406 filename = arg2[:colon].rstrip()
407 arg2 = arg2[colon+1:].lstrip()
408 try:
409 lineno = int(arg2)
410 except ValueError:
411 print >>self.stdout, '*** Bad lineno:', arg2
412 return
413 if convert:
414 filename, lineno = self.doc_to_code(filename, lineno)
415 filename = os.path.split(filename)[1]
416 lineno = int(lineno)
417 f = self.lookupmodule(filename)
418 if not f:
419 print >>self.stdout, '*** ', repr(filename),
420 print >>self.stdout, 'not found from sys.path'
421 return
422 else:
423 filename = f
424 # SPdb
425 #arg = arg[colon+1:].lstrip()
426 #try:
427 # lineno = int(arg)
428 #except ValueError, msg:
429 # print >>self.stdout, '*** Bad lineno:', arg
430 # return
431 # /SPdb
432 else:
433 # no colon; can be lineno or function
434 try:
435 lineno = int(arg2)
436 if convert:
437 lineno = int(self.doc_to_code('', lineno).line)
438 except ValueError:
439 try:
440 func = eval(arg2,
441 self.curframe.f_globals,
442 self.curframe_locals)
443 except:
444 func = arg2
445 try:
446 if hasattr(func, 'im_func'):
447 func = func.im_func
448 code = func.func_code
449 #use co_name to identify the bkpt (function names
450 #could be aliased, but co_name is invariant)
451 funcname = code.co_name
452 lineno = code.co_firstlineno
453 filename = code.co_filename
454 except:
455 # last thing to try
456 (ok, filename, ln) = self.lineinfo(arg2)
457 if not ok:
458 print >>self.stdout, '*** The specified object',
459 print >>self.stdout, repr(arg2),
460 print >>self.stdout, 'is not a function'
461 print >>self.stdout, 'or was not found along sys.path.'
462 return
463 funcname = ok # ok contains a function name
464 lineno = int(ln)
465 # /SPdb
466 if not filename:
467 filename = self.defaultFile()
468 # Check for reasonable breakpoint
469 line = self.checkline(filename, lineno)
470 if line:
471 # now set the break point
472 err = self.set_break(filename, line, temporary, cond, funcname)
473 if err: print >>self.stdout, '***', err
474 else:
475 bp = self.get_breaks(filename, line)[-1]
476 # SPdb
477 sync = self.code_to_doc(filename, lineno)
478 if sync == (None, None):
479 print >>self.stdout, "Breakpoint %d at %s:%d" % (bp.number,
480 bp.file,
481 bp.line)
482 bp.doc_file = None
483 bp.doc_line = None
484 else:
485 print >>self.stdout, "Breakpoint %d at %s:%d (%s:%d)" % (bp.number,
486 bp.file,
487 bp.line,
488 sync.file,
489 sync.line)
490 bp.doc_file = sync.file
491 bp.doc_line = sync.line
492 # /SPdb
493
494 do_b = do_break
495
496
497 def do_clear(self, arg):
498 """Three possibilities, tried in this order:
499 clear -> clear all breaks, ask for confirmation
500 clear file:lineno -> clear all breaks at file:lineno
501 clear bpno bpno ... -> clear breakpoints by number"""
502 if not arg:
503 try:
504 reply = raw_input('Clear all breaks? ')
505 except EOFError:
506 reply = 'no'
507 reply = reply.strip().lower()
508 if reply in ('y', 'yes'):
509 self.clear_all_breaks()
510 return
511 if ':' in arg:
512 # Make sure it works for "clear C:\foo\bar.py:12"
513 i = arg.rfind(':')
514 # SPdb
515 filename = arg[:i].strip()
516 arg = arg[i+1:]
517 if filename.startswith(self._doc_command_char):
518 filename = filename.lstrip(self._doc_command_char_stripset)
519 filename, arg = self.doc_to_code(filename, int(arg))
520 # /SPdb
521 try:
522 lineno = int(arg)
523 except ValueError:
524 err = "Invalid line number (%s)" % arg
525 else:
526 err = self.clear_break(filename, lineno)
527 if err: print >>self.stdout, '***', err
528 return
529 numberlist = arg.split()
530 for i in numberlist:
531 try:
532 i = int(i)
533 except ValueError:
534 print >>self.stdout, 'Breakpoint index %r is not a number' % i
535 continue
536
537 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
538 print >>self.stdout, 'No breakpoint numbered', i
539 continue
540 err = self.clear_bpbynumber(i)
541 if err:
542 print >>self.stdout, '***', err
543 else:
544 print >>self.stdout, 'Deleted breakpoint', i
545
546 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
547
548
549 def do_jump(self, arg):
550 if self.curindex + 1 != len(self.stack):
551 print >>self.stdout, "*** You can only jump within the bottom frame"
552 return
553 # SPdb
554 if arg.startswith(self._doc_command_char):
555 convert = True
556 if ':' in arg:
557 doc_fname, arg = arg.lstrip(self._doc_command_char_stripset).split(':', 1)
558 else:
559 doc_fname = ''
560 arg = arg.lstrip(self._doc_command_char_stripset)
561 else:
562 convert = False
563 # /SPdb
564 try:
565 arg = int(arg)
566 # SPdb
567 if convert:
568 arg = int(self.doc_to_code(doc_fname, arg).line)
569 # /SPdb
570 except ValueError:
571 print >>self.stdout, "*** The 'jump' command requires a line number."
572 else:
573 try:
574 # Do the jump, fix up our copy of the stack, and display the
575 # new position
576 self.curframe.f_lineno = arg
577 self.stack[self.curindex] = self.stack[self.curindex][0], arg
578 self.print_stack_entry(self.stack[self.curindex])
579 # SPdb
580 except ValueError as e:
581 print >>self.stdout, '*** Jump failed:', e
582 # /SPdb
583
584 do_j = do_jump
585
586
587 def do_list(self, arg):
588 self.lastcmd = 'list'
589 last = None
590 if arg:
591 # SPdb
592 arg = arg.strip()
593 if arg.startswith(self._doc_command_char):
594 convert = True
595 if ':' in arg:
596 doc_fname, arg2 = arg.lstrip(self._doc_command_char_stripset).split(':', 1)
597 else:
598 doc_fname = ''
599 arg2 = arg.lstrip(self._doc_command_char_stripset)
600 else:
601 convert = False
602 arg2 = arg
603 # /SPdb
604 try:
605 # SPdb
606 x = eval(arg2, {}, {})
607 # /SPdb
608 if type(x) == type(()):
609 first, last = x
610 first = int(first)
611 last = int(last)
612 # SPdb
613 if convert:
614 first = int(self.doc_to_code(doc_fname, first).line)
615 last = int(self.doc_to_code(doc_fname, last).line)
616 # /SPdb
617 if last < first:
618 # Assume it's a count
619 last = first + last
620 else:
621 # SPdb
622 first = int(x)
623 if convert:
624 first = int(self.doc_to_code(doc_fname, first).line)
625 first = max(1, first - 5)
626 # /SPdb
627 except:
628 print >>self.stdout, '*** Error in argument:', repr(arg)
629 return
630 elif self.lineno is None:
631 first = max(1, self.curframe.f_lineno - 5)
632 else:
633 first = self.lineno + 1
634 if last is None:
635 last = first + 10
636 filename = self.curframe.f_code.co_filename
637 breaklist = self.get_file_breaks(filename)
638 try:
639 # SPdb
640 self._last_doc_fname = None
641 # /SPdb
642 for lineno in range(first, last+1):
643 line = linecache.getline(filename, lineno,
644 self.curframe.f_globals)
645 if not line:
646 print >>self.stdout, self._eof_template
647 break
648 else:
649 s = repr(lineno).rjust(3)
650 if len(s) < 4: s = s + ' '
651 if lineno in breaklist: s = s + 'B'
652 else: s = s + ' '
653 # SPdb
654 if lineno == self.curframe.f_lineno:
655 s = s + '->'
656 else:
657 s = s + ' '
658 f, l = self.code_to_doc(filename, lineno)
659 if f == self.main_doc_fname:
660 s = self._format_line_main_doc(s, l)
661 elif f:
662 s = self._format_line_other_doc(s, l)
663 else:
664 s = self._format_line_no_doc(s)
665 if f != self._last_doc_fname:
666 self._last_doc_fname = f
667 if f is not None:
668 print(self._doc_switch_template.format(f))
669 print >>self.stdout, s + ' ' + line,
670 # /SPdb
671 self.lineno = lineno
672 except KeyboardInterrupt:
673 pass
674
675 do_l = do_list
676
677
678 def format_stack_entry(self, frame_lineno, lprefix=': '):
679 import linecache, repr
680 frame, lineno = frame_lineno
681 filename = self.canonic(frame.f_code.co_filename)
682 s = '%s(%r)' % (filename, lineno)
683 if frame.f_code.co_name:
684 s = s + frame.f_code.co_name
685 else:
686 s = s + "<lambda>"
687 if '__args__' in frame.f_locals:
688 args = frame.f_locals['__args__']
689 else:
690 args = None
691 if args:
692 s = s + repr.repr(args)
693 else:
694 s = s + '()'
695 if '__return__' in frame.f_locals:
696 rv = frame.f_locals['__return__']
697 s = s + '->'
698 s = s + repr.repr(rv)
699 line = linecache.getline(filename, lineno, frame.f_globals)
700 # SPdb
701 sync = self.code_to_doc(frame.f_code.co_filename, lineno)
702 if sync == (None, None):
703 sync_info = ''
704 else:
705 sync_info = ' ({0}:{1})'.format(sync.file, sync.line)
706 if line: s = s + sync_info + lprefix + line.strip()
707 # /SPdb
708 return s
709
710
711 else:
712
713 def bpformat(self, bp):
714 if bp.temporary:
715 disp = 'del '
716 else:
717 disp = 'keep '
718 if bp.enabled:
719 disp = disp + 'yes '
720 else:
721 disp = disp + 'no '
722 # SPdb
723 if bp.doc_file is None:
724 ret = '%-4dbreakpoint %s at %s:%d' % (bp.number, disp,
725 bp.file, bp.line)
726 else:
727 ret = '%-4dbreakpoint %s at %s:%d (%s:%d)' % (bp.number, disp,
728 bp.file, bp.line,
729 bp.doc_file, bp.doc_line)
730 # /SPdb
731 if bp.cond:
732 ret += '\n\tstop only if %s' % (bp.cond,)
733 if bp.ignore:
734 ret += '\n\tignore next %d hits' % (bp.ignore,)
735 if bp.hits:
736 if bp.hits > 1:
737 ss = 's'
738 else:
739 ss = ''
740 ret += '\n\tbreakpoint already hit %d time%s' % (bp.hits, ss)
741 return ret
742
743
744 def do_break(self, arg, temporary = 0):
745 """b(reak) [ ([filename:]lineno | function) [, condition] ]
746 Without argument, list all breaks.
747
748 With a line number argument, set a break at this line in the
749 current file. With a function name, set a break at the first
750 executable line of that function. If a second argument is
751 present, it is a string specifying an expression which must
752 evaluate to true before the breakpoint is honored.
753
754 The line number may be prefixed with a filename and a colon,
755 to specify a breakpoint in another file (probably one that
756 hasn't been loaded yet). The file is searched for on
757 sys.path; the .py suffix may be omitted.
758 """
759 if not arg:
760 if self.breaks: # There's at least one
761 self.message("Num Type Disp Enb Where")
762 for bp in bdb.Breakpoint.bpbynumber:
763 if bp:
764 self.message(self.bpformat(bp))
765 return
766 # parse arguments; comma has lowest precedence
767 # and cannot occur in filename
768 filename = None
769 lineno = None
770 cond = None
771 comma = arg.find(',')
772 if comma > 0:
773 # parse stuff after comma: "condition"
774 cond = arg[comma+1:].lstrip()
775 arg = arg[:comma].rstrip()
776 # SPdb
777 arg = arg.strip()
778 if arg.startswith(self._doc_command_char):
779 convert = True
780 arg2 = arg.lstrip(self._doc_command_char_stripset)
781 else:
782 convert = False
783 arg2 = arg
784 # parse stuff before comma: [filename:]lineno | function
785 colon = arg2.rfind(':')
786 funcname = None
787 if colon >= 0:
788 filename = arg2[:colon].rstrip()
789 arg2 = arg2[colon+1:].lstrip()
790 try:
791 lineno = int(arg2)
792 except ValueError:
793 self.error('Bad lineno: %s' % arg2)
794 return
795 if convert:
796 filename, lineno = self.doc_to_code(filename, lineno)
797 filename = os.path.split(filename)[1]
798 lineno = int(lineno)
799 f = self.lookupmodule(filename)
800 if not f:
801 self.error('%r not found from sys.path' % filename)
802 return
803 else:
804 filename = f
805 # SPdb
806 #arg = arg[colon+1:].lstrip()
807 #try:
808 # lineno = int(arg)
809 #except ValueError:
810 # self.error('Bad lineno: %s' % arg)
811 # return
812 # SPdb
813 else:
814 # no colon; can be lineno or function
815 try:
816 lineno = int(arg2)
817 if convert:
818 lineno = int(self.doc_to_code('', lineno).line)
819 except ValueError:
820 try:
821 func = eval(arg2,
822 self.curframe.f_globals,
823 self.curframe_locals)
824 except:
825 func = arg2
826 try:
827 if hasattr(func, '__func__'):
828 func = func.__func__
829 code = func.__code__
830 #use co_name to identify the bkpt (function names
831 #could be aliased, but co_name is invariant)
832 funcname = code.co_name
833 lineno = code.co_firstlineno
834 filename = code.co_filename
835 except:
836 # last thing to try
837 (ok, filename, ln) = self.lineinfo(arg2)
838 if not ok:
839 self.error('The specified object %r is not a function '
840 'or was not found along sys.path.' % arg2)
841 return
842 funcname = ok # ok contains a function name
843 lineno = int(ln)
844 # /SPdb
845 if not filename:
846 filename = self.defaultFile()
847 # Check for reasonable breakpoint
848 line = self.checkline(filename, lineno)
849 if line:
850 # now set the break point
851 err = self.set_break(filename, line, temporary, cond, funcname)
852 if err:
853 self.error(err, file=self.stdout)
854 else:
855 bp = self.get_breaks(filename, line)[-1]
856 # SPdb
857 sync = self.code_to_doc(filename, lineno)
858 if sync == (None, None):
859 self.message("Breakpoint %d at %s:%d" %
860 (bp.number, bp.file, bp.line))
861 bp.doc_file = None
862 bp.doc_line = None
863 else:
864 self.message("Breakpoint %d at %s:%d (%s:%d)" %
865 (bp.number, bp.file, bp.line,
866 sync.file, sync.line))
867 bp.doc_file = sync.file
868 bp.doc_line = sync.line
869 # /SPdb
870
871 do_b = do_break
872
873
874 def do_clear(self, arg):
875 """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
876 With a space separated list of breakpoint numbers, clear
877 those breakpoints. Without argument, clear all breaks (but
878 first ask confirmation). With a filename:lineno argument,
879 clear all breaks at that line in that file.
880 """
881 if not arg:
882 try:
883 reply = input('Clear all breaks? ')
884 except EOFError:
885 reply = 'no'
886 reply = reply.strip().lower()
887 if reply in ('y', 'yes'):
888 bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
889 self.clear_all_breaks()
890 for bp in bplist:
891 self.message('Deleted %s' % bp)
892 return
893 if ':' in arg:
894 # Make sure it works for "clear C:\foo\bar.py:12"
895 i = arg.rfind(':')
896 # SPdb
897 filename = arg[:i].strip()
898 arg = arg[i+1:]
899 if filename.startswith(self._doc_command_char):
900 filename = filename.lstrip(self._doc_command_char_stripset)
901 filename, arg = self.doc_to_code(filename, int(arg))
902 # /SPdb
903 try:
904 lineno = int(arg)
905 except ValueError:
906 err = "Invalid line number (%s)" % arg
907 else:
908 bplist = self.get_breaks(filename, lineno)
909 err = self.clear_break(filename, lineno)
910 if err:
911 self.error(err)
912 else:
913 for bp in bplist:
914 self.message('Deleted %s' % bp)
915 return
916 numberlist = arg.split()
917 for i in numberlist:
918 try:
919 bp = self.get_bpbynumber(i)
920 except ValueError as err:
921 self.error(err)
922 else:
923 self.clear_bpbynumber(i)
924 self.message('Deleted %s' % bp)
925
926 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
927
928
929 def do_jump(self, arg):
930 """j(ump) lineno
931 Set the next line that will be executed. Only available in
932 the bottom-most frame. This lets you jump back and execute
933 code again, or jump forward to skip code that you don't want
934 to run.
935
936 It should be noted that not all jumps are allowed -- for
937 instance it is not possible to jump into the middle of a
938 for loop or out of a finally clause.
939 """
940 if self.curindex + 1 != len(self.stack):
941 self.error('You can only jump within the bottom frame')
942 return
943 # SPdb
944 if arg.startswith(self._doc_command_char):
945 convert = True
946 if ':' in arg:
947 doc_fname, arg = arg.lstrip(self._doc_command_char_stripset).split(':', 1)
948 else:
949 doc_fname = ''
950 arg = arg.lstrip(self._doc_command_char_stripset)
951 else:
952 convert = False
953 # /SPdb
954 try:
955 arg = int(arg)
956 # SPdb
957 if convert:
958 arg = int(self.doc_to_code(doc_fname, arg).line)
959 # /SPdb
960 except ValueError:
961 self.error("The 'jump' command requires a line number")
962 else:
963 try:
964 # Do the jump, fix up our copy of the stack, and display the
965 # new position
966 self.curframe.f_lineno = arg
967 self.stack[self.curindex] = self.stack[self.curindex][0], arg
968 self.print_stack_entry(self.stack[self.curindex])
969 except ValueError as e:
970 self.error('Jump failed: %s' % e)
971
972 do_j = do_jump
973
974
975 def do_list(self, arg):
976 """l(ist) [first [,last] | .]
977
978 List source code for the current file. Without arguments,
979 list 11 lines around the current line or continue the previous
980 listing. With . as argument, list 11 lines around the current
981 line. With one argument, list 11 lines starting at that line.
982 With two arguments, list the given range; if the second
983 argument is less than the first, it is a count.
984
985 The current line in the current frame is indicated by "->".
986 If an exception is being debugged, the line where the
987 exception was originally raised or propagated is indicated by
988 ">>", if it differs from the current line.
989 """
990 self.lastcmd = 'list'
991 last = None
992 if arg and arg != '.':
993 try:
994 # SPdb
995 arg = arg.strip()
996 if arg.startswith(self._doc_command_char):
997 convert = True
998 if ':' in arg:
999 doc_fname, arg2 = arg.lstrip(self._doc_command_char_stripset).split(':', 1)
1000 else:
1001 doc_fname = ''
1002 arg2 = arg.lstrip(self._doc_command_char_stripset)
1003 else:
1004 convert = False
1005 arg2 = arg
1006 if ',' in arg2:
1007 first, last = arg2.split(',')
1008 first = int(first.strip())
1009 last = int(last.strip())
1010 if convert:
1011 first = int(self.doc_to_code(doc_fname, first).line)
1012 last = int(self.doc_to_code(doc_fname, last).line)
1013 if last < first:
1014 # assume it's a count
1015 last = first + last
1016 else:
1017 first = int(arg2.strip())
1018 if convert:
1019 first = int(self.doc_to_code(doc_fname, first).line)
1020 first = max(1, first - 5)
1021 # /SPdb
1022 except ValueError:
1023 self.error('Error in argument: %r' % arg)
1024 return
1025 elif self.lineno is None or arg == '.':
1026 first = max(1, self.curframe.f_lineno - 5)
1027 else:
1028 first = self.lineno + 1
1029 if last is None:
1030 last = first + 10
1031 filename = self.curframe.f_code.co_filename
1032 breaklist = self.get_file_breaks(filename)
1033 try:
1034 lines = linecache.getlines(filename, self.curframe.f_globals)
1035 # SPdb
1036 self._print_lines(filename, lines[first-1:last], first, last,
1037 breaklist, self.curframe)
1038 # /SPdb
1039 self.lineno = min(last, len(lines))
1040 # SPdb
1041 #if len(lines) < last:
1042 # self.message('[EOF]')
1043 # /SPdb
1044 except KeyboardInterrupt:
1045 pass
1046
1047 do_l = do_list
1048
1049
1050 def do_longlist(self, arg):
1051 """longlist | ll
1052 List the whole source code for the current function or frame.
1053 """
1054 filename = self.curframe.f_code.co_filename
1055 breaklist = self.get_file_breaks(filename)
1056 try:
1057 lines, lineno = getsourcelines(self.curframe)
1058 except IOError as err:
1059 self.error(err)
1060 return
1061 # SPdb
1062 self._print_lines(filename, lines, lineno, lineno + len(lines) - 1,
1063 breaklist, self.curframe)
1064 # /SPdb
1065
1066 do_ll = do_longlist
1067
1068
1069 def do_source(self, arg):
1070 """source expression
1071 Try to get source code for the given object and display it.
1072 """
1073 try:
1074 obj = self._getval(arg)
1075 except:
1076 return
1077 try:
1078 lines, lineno = getsourcelines(obj)
1079 except (IOError, TypeError) as err:
1080 self.error(err)
1081 return
1082 self._print_lines(lines, lineno)
1083
1084
1085 # SPdb added filename, last args; renames start -> first # /SPdb
1086 def _print_lines(self, filename, lines, first, last, breaks=(), frame=None):
1087 """Print a range of lines."""
1088 if frame:
1089 current_lineno = frame.f_lineno
1090 exc_lineno = self.tb_lineno.get(frame, -1)
1091 else:
1092 current_lineno = exc_lineno = -1
1093 # SPdb
1094 self._last_doc_fname = None
1095 # /Spdb
1096 for lineno, line in enumerate(lines, first):
1097 s = str(lineno).rjust(3)
1098 if len(s) < 4:
1099 s += ' '
1100 if lineno in breaks:
1101 s += 'B'
1102 else:
1103 s += ' '
1104 # SPdb
1105 if lineno == current_lineno:
1106 s += '->'
1107 elif lineno == exc_lineno:
1108 s += '>>'
1109 else:
1110 s += ' '
1111 f, l = self.code_to_doc(filename, lineno)
1112 if f == self.main_doc_fname:
1113 s = self._format_line_main_doc(s, l)
1114 elif f:
1115 s = self._format_line_other_doc(s, l)
1116 else:
1117 s = self._format_line_no_doc(s)
1118 if f != self._last_doc_fname:
1119 self._last_doc_fname = f
1120 if f is not None:
1121 self.message(self._doc_switch_template.format(f))
1122 self.message(s + ' ' + line.rstrip())
1123 # /SPdb
1124 # SPdb
1125 if len(lines) < last - first + 1:
1126 self.message(self._eof_template)
1127 # /SPdb
1128
1129
1130 def format_stack_entry(self, frame_lineno, lprefix=': '):
1131 import linecache, reprlib
1132 frame, lineno = frame_lineno
1133 filename = self.canonic(frame.f_code.co_filename)
1134 s = '%s(%r)' % (filename, lineno)
1135 if frame.f_code.co_name:
1136 s += frame.f_code.co_name
1137 else:
1138 s += "<lambda>"
1139 if '__args__' in frame.f_locals:
1140 args = frame.f_locals['__args__']
1141 else:
1142 args = None
1143 if args:
1144 s += reprlib.repr(args)
1145 else:
1146 s += '()'
1147 if '__return__' in frame.f_locals:
1148 rv = frame.f_locals['__return__']
1149 s += '->'
1150 s += reprlib.repr(rv)
1151 line = linecache.getline(filename, lineno, frame.f_globals)
1152 # SPdb
1153 sync = self.code_to_doc(frame.f_code.co_filename, lineno)
1154 if sync == (None, None):
1155 sync_info = ''
1156 else:
1157 sync_info = ' ({0}:{1})'.format(sync.file, sync.line)
1158 # /SPdb
1159 if line:
1160 # SPdb
1161 s += sync_info
1162 # /Spdb
1163 s += lprefix + line.strip()
1164 return s
1165
1166
1167
1168
1169 if sys.version_info.major == 2:
1170
1171 # Simplified interface
1172
1173 def run(statement, globals=None, locals=None):
1174 SyncPdb().run(statement, globals, locals)
1175
1176 def runeval(expression, globals=None, locals=None):
1177 return SyncPdb().runeval(expression, globals, locals)
1178
1179 def runctx(statement, globals, locals):
1180 # B/W compatibility
1181 run(statement, globals, locals)
1182
1183 def runcall(*args, **kwds):
1184 return SyncPdb().runcall(*args, **kwds)
1185
1186 def set_trace():
1187 SyncPdb().set_trace(sys._getframe().f_back)
1188
1189 # Post-Mortem interface
1190
1191 def post_mortem(t=None):
1192 # handling the default
1193 if t is None:
1194 # sys.exc_info() returns (type, value, traceback) if an exception is
1195 # being handled, otherwise it returns None
1196 t = sys.exc_info()[2]
1197 if t is None:
1198 raise ValueError("A valid traceback must be passed if no "
1199 "exception is being handled")
1200
1201 p = SyncPdb()
1202 p.reset()
1203 p.interaction(None, t)
1204
1205 def pm():
1206 post_mortem(sys.last_traceback)
1207
1208
1209 # Main program for testing
1210
1211 TESTCMD = 'import x; x.main()'
1212
1213 def test():
1214 run(TESTCMD)
1215
1216 # print help
1217 def help():
1218 for dirname in sys.path:
1219 fullname = os.path.join(dirname, 'pdb.doc')
1220 if os.path.exists(fullname):
1221 sts = os.system('${PAGER-more} '+fullname)
1222 # SPdb
1223 if sts: print('*** Pager exit status: {0}'.format(sts))
1224 # /SPdb
1225 break
1226 else:
1227 # SPdb
1228 print('Sorry, can\'t find the help file "pdb.doc" along the Python search path')
1229 # /SPdb
1230
1231 else:
1232
1233 # Collect all command help into docstring, if not run with -OO
1234
1235 if __doc__ is not None:
1236 # unfortunately we can't guess this order from the class definition
1237 _help_order = [
1238 'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
1239 'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
1240 'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
1241 'args', 'print', 'pp', 'whatis', 'source', 'display', 'undisplay',
1242 'interact', 'alias', 'unalias', 'debug', 'quit',
1243 ]
1244
1245 for _command in _help_order:
1246 __doc__ += getattr(SyncPdb, 'do_' + _command).__doc__.strip() + '\n\n'
1247 __doc__ += SyncPdb.help_exec.__doc__
1248
1249 del _help_order, _command
1250
1251
1252 # Simplified interface
1253
1254 def run(statement, globals=None, locals=None):
1255 SyncPdb().run(statement, globals, locals)
1256
1257 def runeval(expression, globals=None, locals=None):
1258 return SyncPdb().runeval(expression, globals, locals)
1259
1260 def runctx(statement, globals, locals):
1261 # B/W compatibility
1262 run(statement, globals, locals)
1263
1264 def runcall(*args, **kwds):
1265 return SyncPdb().runcall(*args, **kwds)
1266
1267 def set_trace():
1268 SyncPdb().set_trace(sys._getframe().f_back)
1269
1270 # Post-Mortem interface
1271
1272 def post_mortem(t=None):
1273 # handling the default
1274 if t is None:
1275 # sys.exc_info() returns (type, value, traceback) if an exception is
1276 # being handled, otherwise it returns None
1277 t = sys.exc_info()[2]
1278 if t is None:
1279 raise ValueError("A valid traceback must be passed if no "
1280 "exception is being handled")
1281
1282 p = SyncPdb()
1283 p.reset()
1284 p.interaction(None, t)
1285
1286 def pm():
1287 post_mortem(sys.last_traceback)
1288
1289
1290 # Main program for testing
1291
1292 TESTCMD = 'import x; x.main()'
1293
1294 def test():
1295 run(TESTCMD)
1296
1297 # print help
1298 def help():
1299 import pydoc
1300 pydoc.pager(__doc__)
1301
1302 _usage = """\
1303 usage: syncpdb.py [-c command] ... pyfile [arg] ...
1304
1305 Debug the Python program given by pyfile.
1306
1307 Initial commands are read from .pdbrc files in your home directory
1308 and in the current directory, if they exist. Commands supplied with
1309 -c are executed after commands from .pdbrc files.
1310
1311 To let the script run until an exception occurs, use "-c continue".
1312 To let the script run up to a given line X in the debugged file, use
1313 "-c 'until X'"."""
1314
1315
1316
1317
1318 if sys.version_info == 2:
1319 def main():
1320 if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
1321 # SPdb
1322 print("usage: syncpdb.py scriptfile [arg] ...")
1323 # /SPdb
1324 sys.exit(2)
1325
1326 mainpyfile = sys.argv[1] # Get script filename
1327 if not os.path.exists(mainpyfile):
1328 # SPdb
1329 print('Error:', mainpyfile, 'does not exist')
1330 # /SPdb
1331 sys.exit(1)
1332
1333 del sys.argv[0] # Hide "pdb.py" from argument list
1334
1335 # Replace pdb's dir with script's dir in front of module search path.
1336 sys.path[0] = os.path.dirname(mainpyfile)
1337
1338 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1339 # modified by the script being debugged. It's a bad idea when it was
1340 # changed by the user from the command line. There is a "restart" command
1341 # which allows explicit specification of command line arguments.
1342 syncpdb = SyncPdb()
1343 while True:
1344 try:
1345 syncpdb._runscript(mainpyfile)
1346 if syncpdb._user_requested_quit:
1347 break
1348 # SPdb
1349 print("The program finished and will be restarted")
1350 # /SPdb
1351 except Restart:
1352 # SPdb
1353 print("Restarting", mainpyfile, "with arguments:")
1354 print("\t" + " ".join(sys.argv[1:]))
1355 # /SPdb
1356 except SystemExit:
1357 # In most cases SystemExit does not warrant a post-mortem session.
1358 # SPdb
1359 print("The program exited via sys.exit(). Exit status: {0}".format(sys.exc_info()[1]))
1360 # /SPdb
1361 except:
1362 traceback.print_exc()
1363 # SPdb
1364 print("Uncaught exception. Entering post mortem debugging")
1365 print("Running 'cont' or 'step' will restart the program")
1366 # /SPdb
1367 t = sys.exc_info()[2]
1368 syncpdb.interaction(None, t)
1369 # SPdb
1370 print("Post mortem debugger finished. The {0} will be restarted".format(mainpyfile))
1371 # /SPdb
1372 else:
1373 def main():
1374 import getopt
1375
1376 opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['--help', '--command='])
1377
1378 if not args:
1379 print(_usage)
1380 sys.exit(2)
1381
1382 commands = []
1383 for opt, optarg in opts:
1384 if opt in ['-h', '--help']:
1385 print(_usage)
1386 sys.exit()
1387 elif opt in ['-c', '--command']:
1388 commands.append(optarg)
1389
1390 mainpyfile = args[0] # Get script filename
1391 if not os.path.exists(mainpyfile):
1392 print('Error:', mainpyfile, 'does not exist')
1393 sys.exit(1)
1394
1395 sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
1396
1397 # Replace pdb's dir with script's dir in front of module search path.
1398 sys.path[0] = os.path.dirname(mainpyfile)
1399
1400 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1401 # modified by the script being debugged. It's a bad idea when it was
1402 # changed by the user from the command line. There is a "restart" command
1403 # which allows explicit specification of command line arguments.
1404 syncpdb = SyncPdb()
1405 syncpdb.rcLines.extend(commands)
1406 while True:
1407 try:
1408 syncpdb._runscript(mainpyfile)
1409 if syncpdb._user_requested_quit:
1410 break
1411 print("The program finished and will be restarted")
1412 except Restart:
1413 print("Restarting", mainpyfile, "with arguments:")
1414 print("\t" + " ".join(args))
1415 except SystemExit:
1416 # In most cases SystemExit does not warrant a post-mortem session.
1417 # SPdb
1418 print("The program exited via sys.exit(). Exit status: {0}".format(sys.exc_info()[1]))
1419 # /SPdb
1420 except:
1421 traceback.print_exc()
1422 print("Uncaught exception. Entering post mortem debugging")
1423 print("Running 'cont' or 'step' will restart the program")
1424 t = sys.exc_info()[2]
1425 syncpdb.interaction(None, t)
1426 print("Post mortem debugger finished. The " + mainpyfile +
1427 " will be restarted")
1428
1429
1430 # When invoked as main program, invoke the debugger on a script
1431 if __name__ == '__main__':
1432 import syncpdb
1433 syncpdb.main()