PageRenderTime 61ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/pdb.py

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