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