PageRenderTime 55ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/python/lib/Lib/pdb.py

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