pdb.py 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  1. #! /usr/bin/env python
  2. """A Python debugger."""
  3. # (See pdb.doc for documentation.)
  4. import sys
  5. import linecache
  6. import cmd
  7. import bdb
  8. from repr import Repr
  9. import os
  10. import re
  11. import pprint
  12. import traceback
  13. # Create a custom safe Repr instance and increase its maxstring.
  14. # The default of 30 truncates error messages too easily.
  15. _repr = Repr()
  16. _repr.maxstring = 200
  17. _saferepr = _repr.repr
  18. __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
  19. "post_mortem", "help"]
  20. def find_function(funcname, filename):
  21. cre = re.compile(r'def\s+%s\s*[(]' % funcname)
  22. try:
  23. fp = open(filename)
  24. except IOError:
  25. return None
  26. # consumer of this info expects the first line to be 1
  27. lineno = 1
  28. answer = None
  29. while 1:
  30. line = fp.readline()
  31. if line == '':
  32. break
  33. if cre.match(line):
  34. answer = funcname, filename, lineno
  35. break
  36. lineno = lineno + 1
  37. fp.close()
  38. return answer
  39. # Interaction prompt line will separate file and call info from code
  40. # text using value of line_prefix string. A newline and arrow may
  41. # be to your liking. You can set it once pdb is imported using the
  42. # command "pdb.line_prefix = '\n% '".
  43. # line_prefix = ': ' # Use this to get the old situation back
  44. line_prefix = '\n-> ' # Probably a better default
  45. class Pdb(bdb.Bdb, cmd.Cmd):
  46. def __init__(self):
  47. bdb.Bdb.__init__(self)
  48. cmd.Cmd.__init__(self)
  49. self.prompt = '(Pdb) '
  50. self.aliases = {}
  51. self.mainpyfile = ''
  52. self._wait_for_mainpyfile = 0
  53. # Try to load readline if it exists
  54. try:
  55. import readline
  56. except ImportError:
  57. pass
  58. # Read $HOME/.pdbrc and ./.pdbrc
  59. self.rcLines = []
  60. if 'HOME' in os.environ:
  61. envHome = os.environ['HOME']
  62. try:
  63. rcFile = open(os.path.join(envHome, ".pdbrc"))
  64. except IOError:
  65. pass
  66. else:
  67. for line in rcFile.readlines():
  68. self.rcLines.append(line)
  69. rcFile.close()
  70. try:
  71. rcFile = open(".pdbrc")
  72. except IOError:
  73. pass
  74. else:
  75. for line in rcFile.readlines():
  76. self.rcLines.append(line)
  77. rcFile.close()
  78. def reset(self):
  79. bdb.Bdb.reset(self)
  80. self.forget()
  81. def forget(self):
  82. self.lineno = None
  83. self.stack = []
  84. self.curindex = 0
  85. self.curframe = None
  86. def setup(self, f, t):
  87. self.forget()
  88. self.stack, self.curindex = self.get_stack(f, t)
  89. self.curframe = self.stack[self.curindex][0]
  90. self.execRcLines()
  91. # Can be executed earlier than 'setup' if desired
  92. def execRcLines(self):
  93. if self.rcLines:
  94. # Make local copy because of recursion
  95. rcLines = self.rcLines
  96. # executed only once
  97. self.rcLines = []
  98. for line in rcLines:
  99. line = line[:-1]
  100. if len(line) > 0 and line[0] != '#':
  101. self.onecmd(line)
  102. # Override Bdb methods
  103. def user_call(self, frame, argument_list):
  104. """This method is called when there is the remote possibility
  105. that we ever need to stop in this function."""
  106. if self._wait_for_mainpyfile:
  107. return
  108. if self.stop_here(frame):
  109. print '--Call--'
  110. self.interaction(frame, None)
  111. def user_line(self, frame):
  112. """This function is called when we stop or break at this line."""
  113. if self._wait_for_mainpyfile:
  114. if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
  115. or frame.f_lineno<= 0):
  116. return
  117. self._wait_for_mainpyfile = 0
  118. self.interaction(frame, None)
  119. def user_return(self, frame, return_value):
  120. """This function is called when a return trap is set here."""
  121. frame.f_locals['__return__'] = return_value
  122. print '--Return--'
  123. self.interaction(frame, None)
  124. def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
  125. """This function is called if an exception occurs,
  126. but only if we are to stop at or just below this level."""
  127. frame.f_locals['__exception__'] = exc_type, exc_value
  128. if type(exc_type) == type(''):
  129. exc_type_name = exc_type
  130. else: exc_type_name = exc_type.__name__
  131. print exc_type_name + ':', _saferepr(exc_value)
  132. self.interaction(frame, exc_traceback)
  133. # General interaction function
  134. def interaction(self, frame, traceback):
  135. self.setup(frame, traceback)
  136. self.print_stack_entry(self.stack[self.curindex])
  137. self.cmdloop()
  138. self.forget()
  139. def default(self, line):
  140. if line[:1] == '!': line = line[1:]
  141. locals = self.curframe.f_locals
  142. globals = self.curframe.f_globals
  143. try:
  144. code = compile(line + '\n', '<stdin>', 'single')
  145. exec code in globals, locals
  146. except:
  147. t, v = sys.exc_info()[:2]
  148. if type(t) == type(''):
  149. exc_type_name = t
  150. else: exc_type_name = t.__name__
  151. print '***', exc_type_name + ':', v
  152. def precmd(self, line):
  153. """Handle alias expansion and ';;' separator."""
  154. if not line.strip():
  155. return line
  156. args = line.split()
  157. while args[0] in self.aliases:
  158. line = self.aliases[args[0]]
  159. ii = 1
  160. for tmpArg in args[1:]:
  161. line = line.replace("%" + str(ii),
  162. tmpArg)
  163. ii = ii + 1
  164. line = line.replace("%*", ' '.join(args[1:]))
  165. args = line.split()
  166. # split into ';;' separated commands
  167. # unless it's an alias command
  168. if args[0] != 'alias':
  169. marker = line.find(';;')
  170. if marker >= 0:
  171. # queue up everything after marker
  172. next = line[marker+2:].lstrip()
  173. self.cmdqueue.append(next)
  174. line = line[:marker].rstrip()
  175. return line
  176. # Command definitions, called by cmdloop()
  177. # The argument is the remaining string on the command line
  178. # Return true to exit from the command loop
  179. do_h = cmd.Cmd.do_help
  180. def do_break(self, arg, temporary = 0):
  181. # break [ ([filename:]lineno | function) [, "condition"] ]
  182. if not arg:
  183. if self.breaks: # There's at least one
  184. print "Num Type Disp Enb Where"
  185. for bp in bdb.Breakpoint.bpbynumber:
  186. if bp:
  187. bp.bpprint()
  188. return
  189. # parse arguments; comma has lowest precedence
  190. # and cannot occur in filename
  191. filename = None
  192. lineno = None
  193. cond = None
  194. comma = arg.find(',')
  195. if comma > 0:
  196. # parse stuff after comma: "condition"
  197. cond = arg[comma+1:].lstrip()
  198. arg = arg[:comma].rstrip()
  199. # parse stuff before comma: [filename:]lineno | function
  200. colon = arg.rfind(':')
  201. funcname = None
  202. if colon >= 0:
  203. filename = arg[:colon].rstrip()
  204. f = self.lookupmodule(filename)
  205. if not f:
  206. print '*** ', repr(filename),
  207. print 'not found from sys.path'
  208. return
  209. else:
  210. filename = f
  211. arg = arg[colon+1:].lstrip()
  212. try:
  213. lineno = int(arg)
  214. except ValueError, msg:
  215. print '*** Bad lineno:', arg
  216. return
  217. else:
  218. # no colon; can be lineno or function
  219. try:
  220. lineno = int(arg)
  221. except ValueError:
  222. try:
  223. func = eval(arg,
  224. self.curframe.f_globals,
  225. self.curframe.f_locals)
  226. except:
  227. func = arg
  228. try:
  229. if hasattr(func, 'im_func'):
  230. func = func.im_func
  231. code = func.func_code
  232. #use co_name to identify the bkpt (function names
  233. #could be aliased, but co_name is invariant)
  234. funcname = code.co_name
  235. lineno = code.co_firstlineno
  236. filename = code.co_filename
  237. except:
  238. # last thing to try
  239. (ok, filename, ln) = self.lineinfo(arg)
  240. if not ok:
  241. print '*** The specified object',
  242. print repr(arg),
  243. print 'is not a function'
  244. print ('or was not found '
  245. 'along sys.path.')
  246. return
  247. funcname = ok # ok contains a function name
  248. lineno = int(ln)
  249. if not filename:
  250. filename = self.defaultFile()
  251. # Check for reasonable breakpoint
  252. line = self.checkline(filename, lineno)
  253. if line:
  254. # now set the break point
  255. err = self.set_break(filename, line, temporary, cond, funcname)
  256. if err: print '***', err
  257. else:
  258. bp = self.get_breaks(filename, line)[-1]
  259. print "Breakpoint %d at %s:%d" % (bp.number,
  260. bp.file,
  261. bp.line)
  262. # To be overridden in derived debuggers
  263. def defaultFile(self):
  264. """Produce a reasonable default."""
  265. filename = self.curframe.f_code.co_filename
  266. if filename == '<string>' and self.mainpyfile:
  267. filename = self.mainpyfile
  268. return filename
  269. do_b = do_break
  270. def do_tbreak(self, arg):
  271. self.do_break(arg, 1)
  272. def lineinfo(self, identifier):
  273. failed = (None, None, None)
  274. # Input is identifier, may be in single quotes
  275. idstring = identifier.split("'")
  276. if len(idstring) == 1:
  277. # not in single quotes
  278. id = idstring[0].strip()
  279. elif len(idstring) == 3:
  280. # quoted
  281. id = idstring[1].strip()
  282. else:
  283. return failed
  284. if id == '': return failed
  285. parts = id.split('.')
  286. # Protection for derived debuggers
  287. if parts[0] == 'self':
  288. del parts[0]
  289. if len(parts) == 0:
  290. return failed
  291. # Best first guess at file to look at
  292. fname = self.defaultFile()
  293. if len(parts) == 1:
  294. item = parts[0]
  295. else:
  296. # More than one part.
  297. # First is module, second is method/class
  298. f = self.lookupmodule(parts[0])
  299. if f:
  300. fname = f
  301. item = parts[1]
  302. answer = find_function(item, fname)
  303. return answer or failed
  304. def checkline(self, filename, lineno):
  305. """Check whether specified line seems to be executable.
  306. Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
  307. line or EOF). Warning: testing is not comprehensive.
  308. """
  309. line = linecache.getline(filename, lineno)
  310. if not line:
  311. print 'End of file'
  312. return 0
  313. line = line.strip()
  314. # Don't allow setting breakpoint at a blank line
  315. if (not line or (line[0] == '#') or
  316. (line[:3] == '"""') or line[:3] == "'''"):
  317. print '*** Blank or comment'
  318. return 0
  319. return lineno
  320. def do_enable(self, arg):
  321. args = arg.split()
  322. for i in args:
  323. try:
  324. i = int(i)
  325. except ValueError:
  326. print 'Breakpoint index %r is not a number' % i
  327. continue
  328. if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
  329. print 'No breakpoint numbered', i
  330. continue
  331. bp = bdb.Breakpoint.bpbynumber[i]
  332. if bp:
  333. bp.enable()
  334. def do_disable(self, arg):
  335. args = arg.split()
  336. for i in args:
  337. try:
  338. i = int(i)
  339. except ValueError:
  340. print 'Breakpoint index %r is not a number' % i
  341. continue
  342. if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
  343. print 'No breakpoint numbered', i
  344. continue
  345. bp = bdb.Breakpoint.bpbynumber[i]
  346. if bp:
  347. bp.disable()
  348. def do_condition(self, arg):
  349. # arg is breakpoint number and condition
  350. args = arg.split(' ', 1)
  351. bpnum = int(args[0].strip())
  352. try:
  353. cond = args[1]
  354. except:
  355. cond = None
  356. bp = bdb.Breakpoint.bpbynumber[bpnum]
  357. if bp:
  358. bp.cond = cond
  359. if not cond:
  360. print 'Breakpoint', bpnum,
  361. print 'is now unconditional.'
  362. def do_ignore(self,arg):
  363. """arg is bp number followed by ignore count."""
  364. args = arg.split()
  365. bpnum = int(args[0].strip())
  366. try:
  367. count = int(args[1].strip())
  368. except:
  369. count = 0
  370. bp = bdb.Breakpoint.bpbynumber[bpnum]
  371. if bp:
  372. bp.ignore = count
  373. if count > 0:
  374. reply = 'Will ignore next '
  375. if count > 1:
  376. reply = reply + '%d crossings' % count
  377. else:
  378. reply = reply + '1 crossing'
  379. print reply + ' of breakpoint %d.' % bpnum
  380. else:
  381. print 'Will stop next time breakpoint',
  382. print bpnum, 'is reached.'
  383. def do_clear(self, arg):
  384. """Three possibilities, tried in this order:
  385. clear -> clear all breaks, ask for confirmation
  386. clear file:lineno -> clear all breaks at file:lineno
  387. clear bpno bpno ... -> clear breakpoints by number"""
  388. if not arg:
  389. try:
  390. reply = raw_input('Clear all breaks? ')
  391. except EOFError:
  392. reply = 'no'
  393. reply = reply.strip().lower()
  394. if reply in ('y', 'yes'):
  395. self.clear_all_breaks()
  396. return
  397. if ':' in arg:
  398. # Make sure it works for "clear C:\foo\bar.py:12"
  399. i = arg.rfind(':')
  400. filename = arg[:i]
  401. arg = arg[i+1:]
  402. try:
  403. lineno = int(arg)
  404. except ValueError:
  405. err = "Invalid line number (%s)" % arg
  406. else:
  407. err = self.clear_break(filename, lineno)
  408. if err: print '***', err
  409. return
  410. numberlist = arg.split()
  411. for i in numberlist:
  412. try:
  413. i = int(i)
  414. except ValueError:
  415. print 'Breakpoint index %r is not a number' % i
  416. continue
  417. if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
  418. print 'No breakpoint numbered', i
  419. continue
  420. err = self.clear_bpbynumber(i)
  421. if err:
  422. print '***', err
  423. else:
  424. print 'Deleted breakpoint', i
  425. do_cl = do_clear # 'c' is already an abbreviation for 'continue'
  426. def do_where(self, arg):
  427. self.print_stack_trace()
  428. do_w = do_where
  429. do_bt = do_where
  430. def do_up(self, arg):
  431. if self.curindex == 0:
  432. print '*** Oldest frame'
  433. else:
  434. self.curindex = self.curindex - 1
  435. self.curframe = self.stack[self.curindex][0]
  436. self.print_stack_entry(self.stack[self.curindex])
  437. self.lineno = None
  438. do_u = do_up
  439. def do_down(self, arg):
  440. if self.curindex + 1 == len(self.stack):
  441. print '*** Newest frame'
  442. else:
  443. self.curindex = self.curindex + 1
  444. self.curframe = self.stack[self.curindex][0]
  445. self.print_stack_entry(self.stack[self.curindex])
  446. self.lineno = None
  447. do_d = do_down
  448. def do_step(self, arg):
  449. self.set_step()
  450. return 1
  451. do_s = do_step
  452. def do_next(self, arg):
  453. self.set_next(self.curframe)
  454. return 1
  455. do_n = do_next
  456. def do_return(self, arg):
  457. self.set_return(self.curframe)
  458. return 1
  459. do_r = do_return
  460. def do_continue(self, arg):
  461. self.set_continue()
  462. return 1
  463. do_c = do_cont = do_continue
  464. def do_jump(self, arg):
  465. if self.curindex + 1 != len(self.stack):
  466. print "*** You can only jump within the bottom frame"
  467. return
  468. try:
  469. arg = int(arg)
  470. except ValueError:
  471. print "*** The 'jump' command requires a line number."
  472. else:
  473. try:
  474. # Do the jump, fix up our copy of the stack, and display the
  475. # new position
  476. self.curframe.f_lineno = arg
  477. self.stack[self.curindex] = self.stack[self.curindex][0], arg
  478. self.print_stack_entry(self.stack[self.curindex])
  479. except ValueError, e:
  480. print '*** Jump failed:', e
  481. do_j = do_jump
  482. def do_debug(self, arg):
  483. sys.settrace(None)
  484. globals = self.curframe.f_globals
  485. locals = self.curframe.f_locals
  486. p = Pdb()
  487. p.prompt = "(%s) " % self.prompt.strip()
  488. print "ENTERING RECURSIVE DEBUGGER"
  489. sys.call_tracing(p.run, (arg, globals, locals))
  490. print "LEAVING RECURSIVE DEBUGGER"
  491. sys.settrace(self.trace_dispatch)
  492. self.lastcmd = p.lastcmd
  493. def do_quit(self, arg):
  494. self._user_requested_quit = 1
  495. self.set_quit()
  496. return 1
  497. do_q = do_quit
  498. do_exit = do_quit
  499. def do_EOF(self, arg):
  500. print
  501. self._user_requested_quit = 1
  502. self.set_quit()
  503. return 1
  504. def do_args(self, arg):
  505. f = self.curframe
  506. co = f.f_code
  507. dict = f.f_locals
  508. n = co.co_argcount
  509. if co.co_flags & 4: n = n+1
  510. if co.co_flags & 8: n = n+1
  511. for i in range(n):
  512. name = co.co_varnames[i]
  513. print name, '=',
  514. if name in dict: print dict[name]
  515. else: print "*** undefined ***"
  516. do_a = do_args
  517. def do_retval(self, arg):
  518. if '__return__' in self.curframe.f_locals:
  519. print self.curframe.f_locals['__return__']
  520. else:
  521. print '*** Not yet returned!'
  522. do_rv = do_retval
  523. def _getval(self, arg):
  524. try:
  525. return eval(arg, self.curframe.f_globals,
  526. self.curframe.f_locals)
  527. except:
  528. t, v = sys.exc_info()[:2]
  529. if isinstance(t, str):
  530. exc_type_name = t
  531. else: exc_type_name = t.__name__
  532. print '***', exc_type_name + ':', repr(v)
  533. raise
  534. def do_p(self, arg):
  535. try:
  536. print repr(self._getval(arg))
  537. except:
  538. pass
  539. def do_pp(self, arg):
  540. try:
  541. pprint.pprint(self._getval(arg))
  542. except:
  543. pass
  544. def do_list(self, arg):
  545. self.lastcmd = 'list'
  546. last = None
  547. if arg:
  548. try:
  549. x = eval(arg, {}, {})
  550. if type(x) == type(()):
  551. first, last = x
  552. first = int(first)
  553. last = int(last)
  554. if last < first:
  555. # Assume it's a count
  556. last = first + last
  557. else:
  558. first = max(1, int(x) - 5)
  559. except:
  560. print '*** Error in argument:', repr(arg)
  561. return
  562. elif self.lineno is None:
  563. first = max(1, self.curframe.f_lineno - 5)
  564. else:
  565. first = self.lineno + 1
  566. if last is None:
  567. last = first + 10
  568. filename = self.curframe.f_code.co_filename
  569. breaklist = self.get_file_breaks(filename)
  570. try:
  571. for lineno in range(first, last+1):
  572. line = linecache.getline(filename, lineno)
  573. if not line:
  574. print '[EOF]'
  575. break
  576. else:
  577. s = repr(lineno).rjust(3)
  578. if len(s) < 4: s = s + ' '
  579. if lineno in breaklist: s = s + 'B'
  580. else: s = s + ' '
  581. if lineno == self.curframe.f_lineno:
  582. s = s + '->'
  583. print s + '\t' + line,
  584. self.lineno = lineno
  585. except KeyboardInterrupt:
  586. pass
  587. do_l = do_list
  588. def do_whatis(self, arg):
  589. try:
  590. value = eval(arg, self.curframe.f_globals,
  591. self.curframe.f_locals)
  592. except:
  593. t, v = sys.exc_info()[:2]
  594. if type(t) == type(''):
  595. exc_type_name = t
  596. else: exc_type_name = t.__name__
  597. print '***', exc_type_name + ':', repr(v)
  598. return
  599. code = None
  600. # Is it a function?
  601. try: code = value.func_code
  602. except: pass
  603. if code:
  604. print 'Function', code.co_name
  605. return
  606. # Is it an instance method?
  607. try: code = value.im_func.func_code
  608. except: pass
  609. if code:
  610. print 'Method', code.co_name
  611. return
  612. # None of the above...
  613. print type(value)
  614. def do_alias(self, arg):
  615. args = arg.split()
  616. if len(args) == 0:
  617. keys = self.aliases.keys()
  618. keys.sort()
  619. for alias in keys:
  620. print "%s = %s" % (alias, self.aliases[alias])
  621. return
  622. if args[0] in self.aliases and len(args) == 1:
  623. print "%s = %s" % (args[0], self.aliases[args[0]])
  624. else:
  625. self.aliases[args[0]] = ' '.join(args[1:])
  626. def do_unalias(self, arg):
  627. args = arg.split()
  628. if len(args) == 0: return
  629. if args[0] in self.aliases:
  630. del self.aliases[args[0]]
  631. # Print a traceback starting at the top stack frame.
  632. # The most recently entered frame is printed last;
  633. # this is different from dbx and gdb, but consistent with
  634. # the Python interpreter's stack trace.
  635. # It is also consistent with the up/down commands (which are
  636. # compatible with dbx and gdb: up moves towards 'main()'
  637. # and down moves towards the most recent stack frame).
  638. def print_stack_trace(self):
  639. try:
  640. for frame_lineno in self.stack:
  641. self.print_stack_entry(frame_lineno)
  642. except KeyboardInterrupt:
  643. pass
  644. def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
  645. frame, lineno = frame_lineno
  646. if frame is self.curframe:
  647. print '>',
  648. else:
  649. print ' ',
  650. print self.format_stack_entry(frame_lineno, prompt_prefix)
  651. # Help methods (derived from pdb.doc)
  652. def help_help(self):
  653. self.help_h()
  654. def help_h(self):
  655. print """h(elp)
  656. Without argument, print the list of available commands.
  657. With a command name as argument, print help about that command
  658. "help pdb" pipes the full documentation file to the $PAGER
  659. "help exec" gives help on the ! command"""
  660. def help_where(self):
  661. self.help_w()
  662. def help_w(self):
  663. print """w(here)
  664. Print a stack trace, with the most recent frame at the bottom.
  665. An arrow indicates the "current frame", which determines the
  666. context of most commands. 'bt' is an alias for this command."""
  667. help_bt = help_w
  668. def help_down(self):
  669. self.help_d()
  670. def help_d(self):
  671. print """d(own)
  672. Move the current frame one level down in the stack trace
  673. (to a newer frame)."""
  674. def help_up(self):
  675. self.help_u()
  676. def help_u(self):
  677. print """u(p)
  678. Move the current frame one level up in the stack trace
  679. (to an older frame)."""
  680. def help_break(self):
  681. self.help_b()
  682. def help_b(self):
  683. print """b(reak) ([file:]lineno | function) [, condition]
  684. With a line number argument, set a break there in the current
  685. file. With a function name, set a break at first executable line
  686. of that function. Without argument, list all breaks. If a second
  687. argument is present, it is a string specifying an expression
  688. which must evaluate to true before the breakpoint is honored.
  689. The line number may be prefixed with a filename and a colon,
  690. to specify a breakpoint in another file (probably one that
  691. hasn't been loaded yet). The file is searched for on sys.path;
  692. the .py suffix may be omitted."""
  693. def help_clear(self):
  694. self.help_cl()
  695. def help_cl(self):
  696. print "cl(ear) filename:lineno"
  697. print """cl(ear) [bpnumber [bpnumber...]]
  698. With a space separated list of breakpoint numbers, clear
  699. those breakpoints. Without argument, clear all breaks (but
  700. first ask confirmation). With a filename:lineno argument,
  701. clear all breaks at that line in that file.
  702. Note that the argument is different from previous versions of
  703. the debugger (in python distributions 1.5.1 and before) where
  704. a linenumber was used instead of either filename:lineno or
  705. breakpoint numbers."""
  706. def help_tbreak(self):
  707. print """tbreak same arguments as break, but breakpoint is
  708. removed when first hit."""
  709. def help_enable(self):
  710. print """enable bpnumber [bpnumber ...]
  711. Enables the breakpoints given as a space separated list of
  712. bp numbers."""
  713. def help_disable(self):
  714. print """disable bpnumber [bpnumber ...]
  715. Disables the breakpoints given as a space separated list of
  716. bp numbers."""
  717. def help_ignore(self):
  718. print """ignore bpnumber count
  719. Sets the ignore count for the given breakpoint number. A breakpoint
  720. becomes active when the ignore count is zero. When non-zero, the
  721. count is decremented each time the breakpoint is reached and the
  722. breakpoint is not disabled and any associated condition evaluates
  723. to true."""
  724. def help_condition(self):
  725. print """condition bpnumber str_condition
  726. str_condition is a string specifying an expression which
  727. must evaluate to true before the breakpoint is honored.
  728. If str_condition is absent, any existing condition is removed;
  729. i.e., the breakpoint is made unconditional."""
  730. def help_step(self):
  731. self.help_s()
  732. def help_s(self):
  733. print """s(tep)
  734. Execute the current line, stop at the first possible occasion
  735. (either in a function that is called or in the current function)."""
  736. def help_next(self):
  737. self.help_n()
  738. def help_n(self):
  739. print """n(ext)
  740. Continue execution until the next line in the current function
  741. is reached or it returns."""
  742. def help_return(self):
  743. self.help_r()
  744. def help_r(self):
  745. print """r(eturn)
  746. Continue execution until the current function returns."""
  747. def help_continue(self):
  748. self.help_c()
  749. def help_cont(self):
  750. self.help_c()
  751. def help_c(self):
  752. print """c(ont(inue))
  753. Continue execution, only stop when a breakpoint is encountered."""
  754. def help_jump(self):
  755. self.help_j()
  756. def help_j(self):
  757. print """j(ump) lineno
  758. Set the next line that will be executed."""
  759. def help_debug(self):
  760. print """debug code
  761. Enter a recursive debugger that steps through the code argument
  762. (which is an arbitrary expression or statement to be executed
  763. in the current environment)."""
  764. def help_list(self):
  765. self.help_l()
  766. def help_l(self):
  767. print """l(ist) [first [,last]]
  768. List source code for the current file.
  769. Without arguments, list 11 lines around the current line
  770. or continue the previous listing.
  771. With one argument, list 11 lines starting at that line.
  772. With two arguments, list the given range;
  773. if the second argument is less than the first, it is a count."""
  774. def help_args(self):
  775. self.help_a()
  776. def help_a(self):
  777. print """a(rgs)
  778. Print the arguments of the current function."""
  779. def help_p(self):
  780. print """p expression
  781. Print the value of the expression."""
  782. def help_pp(self):
  783. print """pp expression
  784. Pretty-print the value of the expression."""
  785. def help_exec(self):
  786. print """(!) statement
  787. Execute the (one-line) statement in the context of
  788. the current stack frame.
  789. The exclamation point can be omitted unless the first word
  790. of the statement resembles a debugger command.
  791. To assign to a global variable you must always prefix the
  792. command with a 'global' command, e.g.:
  793. (Pdb) global list_options; list_options = ['-l']
  794. (Pdb)"""
  795. def help_quit(self):
  796. self.help_q()
  797. def help_q(self):
  798. print """q(uit) or exit - Quit from the debugger.
  799. The program being executed is aborted."""
  800. help_exit = help_q
  801. def help_whatis(self):
  802. print """whatis arg
  803. Prints the type of the argument."""
  804. def help_EOF(self):
  805. print """EOF
  806. Handles the receipt of EOF as a command."""
  807. def help_alias(self):
  808. print """alias [name [command [parameter parameter ...] ]]
  809. Creates an alias called 'name' the executes 'command'. The command
  810. must *not* be enclosed in quotes. Replaceable parameters are
  811. indicated by %1, %2, and so on, while %* is replaced by all the
  812. parameters. If no command is given, the current alias for name
  813. is shown. If no name is given, all aliases are listed.
  814. Aliases may be nested and can contain anything that can be
  815. legally typed at the pdb prompt. Note! You *can* override
  816. internal pdb commands with aliases! Those internal commands
  817. are then hidden until the alias is removed. Aliasing is recursively
  818. applied to the first word of the command line; all other words
  819. in the line are left alone.
  820. Some useful aliases (especially when placed in the .pdbrc file) are:
  821. #Print instance variables (usage "pi classInst")
  822. alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
  823. #Print instance variables in self
  824. alias ps pi self
  825. """
  826. def help_unalias(self):
  827. print """unalias name
  828. Deletes the specified alias."""
  829. def help_pdb(self):
  830. help()
  831. def lookupmodule(self, filename):
  832. """Helper function for break/clear parsing -- may be overridden.
  833. lookupmodule() translates (possibly incomplete) file or module name
  834. into an absolute file name.
  835. """
  836. if os.path.isabs(filename) and os.path.exists(filename):
  837. return filename
  838. f = os.path.join(sys.path[0], filename)
  839. if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
  840. return f
  841. root, ext = os.path.splitext(filename)
  842. if ext == '':
  843. filename = filename + '.py'
  844. if os.path.isabs(filename):
  845. return filename
  846. for dirname in sys.path:
  847. while os.path.islink(dirname):
  848. dirname = os.readlink(dirname)
  849. fullname = os.path.join(dirname, filename)
  850. if os.path.exists(fullname):
  851. return fullname
  852. return None
  853. def _runscript(self, filename):
  854. # Start with fresh empty copy of globals and locals and tell the script
  855. # that it's being run as __main__ to avoid scripts being able to access
  856. # the pdb.py namespace.
  857. globals_ = {"__name__" : "__main__"}
  858. locals_ = globals_
  859. # When bdb sets tracing, a number of call and line events happens
  860. # BEFORE debugger even reaches user's code (and the exact sequence of
  861. # events depends on python version). So we take special measures to
  862. # avoid stopping before we reach the main script (see user_line and
  863. # user_call for details).
  864. self._wait_for_mainpyfile = 1
  865. self.mainpyfile = self.canonic(filename)
  866. self._user_requested_quit = 0
  867. statement = 'execfile( "%s")' % filename
  868. self.run(statement, globals=globals_, locals=locals_)
  869. # Simplified interface
  870. def run(statement, globals=None, locals=None):
  871. Pdb().run(statement, globals, locals)
  872. def runeval(expression, globals=None, locals=None):
  873. return Pdb().runeval(expression, globals, locals)
  874. def runctx(statement, globals, locals):
  875. # B/W compatibility
  876. run(statement, globals, locals)
  877. def runcall(*args, **kwds):
  878. return Pdb().runcall(*args, **kwds)
  879. def set_trace():
  880. Pdb().set_trace(sys._getframe().f_back)
  881. # Post-Mortem interface
  882. def post_mortem(t):
  883. p = Pdb()
  884. p.reset()
  885. while t.tb_next is not None:
  886. t = t.tb_next
  887. p.interaction(t.tb_frame, t)
  888. def pm():
  889. post_mortem(sys.last_traceback)
  890. # Main program for testing
  891. TESTCMD = 'import x; x.main()'
  892. def test():
  893. run(TESTCMD)
  894. # print help
  895. def help():
  896. for dirname in sys.path:
  897. fullname = os.path.join(dirname, 'pdb.doc')
  898. if os.path.exists(fullname):
  899. sts = os.system('${PAGER-more} '+fullname)
  900. if sts: print '*** Pager exit status:', sts
  901. break
  902. else:
  903. print 'Sorry, can\'t find the help file "pdb.doc"',
  904. print 'along the Python search path'
  905. def main():
  906. if not sys.argv[1:]:
  907. print "usage: pdb.py scriptfile [arg] ..."
  908. sys.exit(2)
  909. mainpyfile = sys.argv[1] # Get script filename
  910. if not os.path.exists(mainpyfile):
  911. print 'Error:', mainpyfile, 'does not exist'
  912. sys.exit(1)
  913. del sys.argv[0] # Hide "pdb.py" from argument list
  914. # Replace pdb's dir with script's dir in front of module search path.
  915. sys.path[0] = os.path.dirname(mainpyfile)
  916. # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
  917. # modified by the script being debugged. It's a bad idea when it was
  918. # changed by the user from the command line. The best approach would be to
  919. # have a "restart" command which would allow explicit specification of
  920. # command line arguments.
  921. pdb = Pdb()
  922. while 1:
  923. try:
  924. pdb._runscript(mainpyfile)
  925. if pdb._user_requested_quit:
  926. break
  927. print "The program finished and will be restarted"
  928. except SystemExit:
  929. # In most cases SystemExit does not warrant a post-mortem session.
  930. print "The program exited via sys.exit(). Exit status: ",
  931. print sys.exc_info()[1]
  932. except:
  933. traceback.print_exc()
  934. print "Uncaught exception. Entering post mortem debugging"
  935. print "Running 'cont' or 'step' will restart the program"
  936. t = sys.exc_info()[2]
  937. while t.tb_next is not None:
  938. t = t.tb_next
  939. pdb.interaction(t.tb_frame,t)
  940. print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
  941. # When invoked as main program, invoke the debugger on a script
  942. if __name__=='__main__':
  943. main()