pdb.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  1. #! /usr/bin/env python3
  2. """
  3. The Python Debugger Pdb
  4. =======================
  5. To use the debugger in its simplest form:
  6. >>> import pdb
  7. >>> pdb.run('<a statement>')
  8. The debugger's prompt is '(Pdb) '. This will stop in the first
  9. function call in <a statement>.
  10. Alternatively, if a statement terminated with an unhandled exception,
  11. you can use pdb's post-mortem facility to inspect the contents of the
  12. traceback:
  13. >>> <a statement>
  14. <exception traceback>
  15. >>> import pdb
  16. >>> pdb.pm()
  17. The commands recognized by the debugger are listed in the next
  18. section. Most can be abbreviated as indicated; e.g., h(elp) means
  19. that 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel',
  20. nor as 'H' or 'Help' or 'HELP'). Optional arguments are enclosed in
  21. square brackets. Alternatives in the command syntax are separated
  22. by a vertical bar (|).
  23. A blank line repeats the previous command literally, except for
  24. 'list', where it lists the next 11 lines.
  25. Commands that the debugger doesn't recognize are assumed to be Python
  26. statements and are executed in the context of the program being
  27. debugged. Python statements can also be prefixed with an exclamation
  28. point ('!'). This is a powerful way to inspect the program being
  29. debugged; it is even possible to change variables or call functions.
  30. When an exception occurs in such a statement, the exception name is
  31. printed but the debugger's state is not changed.
  32. The debugger supports aliases, which can save typing. And aliases can
  33. have parameters (see the alias help entry) which allows one a certain
  34. level of adaptability to the context under examination.
  35. Multiple commands may be entered on a single line, separated by the
  36. pair ';;'. No intelligence is applied to separating the commands; the
  37. input is split at the first ';;', even if it is in the middle of a
  38. quoted string.
  39. If a file ".pdbrc" exists in your home directory or in the current
  40. directory, it is read in and executed as if it had been typed at the
  41. debugger prompt. This is particularly useful for aliases. If both
  42. files exist, the one in the home directory is read first and aliases
  43. defined there can be overridden by the local file. This behavior can be
  44. disabled by passing the "readrc=False" argument to the Pdb constructor.
  45. Aside from aliases, the debugger is not directly programmable; but it
  46. is implemented as a class from which you can derive your own debugger
  47. class, which you can make as fancy as you like.
  48. Debugger commands
  49. =================
  50. """
  51. # NOTE: the actual command documentation is collected from docstrings of the
  52. # commands and is appended to __doc__ after the class has been defined.
  53. import os
  54. import re
  55. import sys
  56. import cmd
  57. import bdb
  58. import dis
  59. import code
  60. import glob
  61. import pprint
  62. import signal
  63. import inspect
  64. import traceback
  65. import linecache
  66. class Restart(Exception):
  67. """Causes a debugger to be restarted for the debugged python program."""
  68. pass
  69. __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
  70. "post_mortem", "help"]
  71. def find_function(funcname, filename):
  72. cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
  73. try:
  74. fp = open(filename)
  75. except OSError:
  76. return None
  77. # consumer of this info expects the first line to be 1
  78. with fp:
  79. for lineno, line in enumerate(fp, start=1):
  80. if cre.match(line):
  81. return funcname, filename, lineno
  82. return None
  83. def getsourcelines(obj):
  84. lines, lineno = inspect.findsource(obj)
  85. if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
  86. # must be a module frame: do not try to cut a block out of it
  87. return lines, 1
  88. elif inspect.ismodule(obj):
  89. return lines, 1
  90. return inspect.getblock(lines[lineno:]), lineno+1
  91. def lasti2lineno(code, lasti):
  92. linestarts = list(dis.findlinestarts(code))
  93. linestarts.reverse()
  94. for i, lineno in linestarts:
  95. if lasti >= i:
  96. return lineno
  97. return 0
  98. class _rstr(str):
  99. """String that doesn't quote its repr."""
  100. def __repr__(self):
  101. return self
  102. # Interaction prompt line will separate file and call info from code
  103. # text using value of line_prefix string. A newline and arrow may
  104. # be to your liking. You can set it once pdb is imported using the
  105. # command "pdb.line_prefix = '\n% '".
  106. # line_prefix = ': ' # Use this to get the old situation back
  107. line_prefix = '\n-> ' # Probably a better default
  108. class Pdb(bdb.Bdb, cmd.Cmd):
  109. _previous_sigint_handler = None
  110. def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
  111. nosigint=False, readrc=True):
  112. bdb.Bdb.__init__(self, skip=skip)
  113. cmd.Cmd.__init__(self, completekey, stdin, stdout)
  114. if stdout:
  115. self.use_rawinput = 0
  116. self.prompt = '(Pdb) '
  117. self.aliases = {}
  118. self.displaying = {}
  119. self.mainpyfile = ''
  120. self._wait_for_mainpyfile = False
  121. self.tb_lineno = {}
  122. # Try to load readline if it exists
  123. try:
  124. import readline
  125. # remove some common file name delimiters
  126. readline.set_completer_delims(' \t\n`@#$%^&*()=+[{]}\\|;:\'",<>?')
  127. except ImportError:
  128. pass
  129. self.allow_kbdint = False
  130. self.nosigint = nosigint
  131. # Read ~/.pdbrc and ./.pdbrc
  132. self.rcLines = []
  133. if readrc:
  134. try:
  135. with open(os.path.expanduser('~/.pdbrc')) as rcFile:
  136. self.rcLines.extend(rcFile)
  137. except OSError:
  138. pass
  139. try:
  140. with open(".pdbrc") as rcFile:
  141. self.rcLines.extend(rcFile)
  142. except OSError:
  143. pass
  144. self.commands = {} # associates a command list to breakpoint numbers
  145. self.commands_doprompt = {} # for each bp num, tells if the prompt
  146. # must be disp. after execing the cmd list
  147. self.commands_silent = {} # for each bp num, tells if the stack trace
  148. # must be disp. after execing the cmd list
  149. self.commands_defining = False # True while in the process of defining
  150. # a command list
  151. self.commands_bnum = None # The breakpoint number for which we are
  152. # defining a list
  153. def sigint_handler(self, signum, frame):
  154. if self.allow_kbdint:
  155. raise KeyboardInterrupt
  156. self.message("\nProgram interrupted. (Use 'cont' to resume).")
  157. self.set_step()
  158. self.set_trace(frame)
  159. def reset(self):
  160. bdb.Bdb.reset(self)
  161. self.forget()
  162. def forget(self):
  163. self.lineno = None
  164. self.stack = []
  165. self.curindex = 0
  166. self.curframe = None
  167. self.tb_lineno.clear()
  168. def setup(self, f, tb):
  169. self.forget()
  170. self.stack, self.curindex = self.get_stack(f, tb)
  171. while tb:
  172. # when setting up post-mortem debugging with a traceback, save all
  173. # the original line numbers to be displayed along the current line
  174. # numbers (which can be different, e.g. due to finally clauses)
  175. lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
  176. self.tb_lineno[tb.tb_frame] = lineno
  177. tb = tb.tb_next
  178. self.curframe = self.stack[self.curindex][0]
  179. # The f_locals dictionary is updated from the actual frame
  180. # locals whenever the .f_locals accessor is called, so we
  181. # cache it here to ensure that modifications are not overwritten.
  182. self.curframe_locals = self.curframe.f_locals
  183. return self.execRcLines()
  184. # Can be executed earlier than 'setup' if desired
  185. def execRcLines(self):
  186. if not self.rcLines:
  187. return
  188. # local copy because of recursion
  189. rcLines = self.rcLines
  190. rcLines.reverse()
  191. # execute every line only once
  192. self.rcLines = []
  193. while rcLines:
  194. line = rcLines.pop().strip()
  195. if line and line[0] != '#':
  196. if self.onecmd(line):
  197. # if onecmd returns True, the command wants to exit
  198. # from the interaction, save leftover rc lines
  199. # to execute before next interaction
  200. self.rcLines += reversed(rcLines)
  201. return True
  202. # Override Bdb methods
  203. def user_call(self, frame, argument_list):
  204. """This method is called when there is the remote possibility
  205. that we ever need to stop in this function."""
  206. if self._wait_for_mainpyfile:
  207. return
  208. if self.stop_here(frame):
  209. self.message('--Call--')
  210. self.interaction(frame, None)
  211. def user_line(self, frame):
  212. """This function is called when we stop or break at this line."""
  213. if self._wait_for_mainpyfile:
  214. if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
  215. or frame.f_lineno <= 0):
  216. return
  217. self._wait_for_mainpyfile = False
  218. if self.bp_commands(frame):
  219. self.interaction(frame, None)
  220. def bp_commands(self, frame):
  221. """Call every command that was set for the current active breakpoint
  222. (if there is one).
  223. Returns True if the normal interaction function must be called,
  224. False otherwise."""
  225. # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
  226. if getattr(self, "currentbp", False) and \
  227. self.currentbp in self.commands:
  228. currentbp = self.currentbp
  229. self.currentbp = 0
  230. lastcmd_back = self.lastcmd
  231. self.setup(frame, None)
  232. for line in self.commands[currentbp]:
  233. self.onecmd(line)
  234. self.lastcmd = lastcmd_back
  235. if not self.commands_silent[currentbp]:
  236. self.print_stack_entry(self.stack[self.curindex])
  237. if self.commands_doprompt[currentbp]:
  238. self._cmdloop()
  239. self.forget()
  240. return
  241. return 1
  242. def user_return(self, frame, return_value):
  243. """This function is called when a return trap is set here."""
  244. if self._wait_for_mainpyfile:
  245. return
  246. frame.f_locals['__return__'] = return_value
  247. self.message('--Return--')
  248. self.interaction(frame, None)
  249. def user_exception(self, frame, exc_info):
  250. """This function is called if an exception occurs,
  251. but only if we are to stop at or just below this level."""
  252. if self._wait_for_mainpyfile:
  253. return
  254. exc_type, exc_value, exc_traceback = exc_info
  255. frame.f_locals['__exception__'] = exc_type, exc_value
  256. # An 'Internal StopIteration' exception is an exception debug event
  257. # issued by the interpreter when handling a subgenerator run with
  258. # 'yield from' or a generator controlled by a for loop. No exception has
  259. # actually occurred in this case. The debugger uses this debug event to
  260. # stop when the debuggee is returning from such generators.
  261. prefix = 'Internal ' if (not exc_traceback
  262. and exc_type is StopIteration) else ''
  263. self.message('%s%s' % (prefix,
  264. traceback.format_exception_only(exc_type, exc_value)[-1].strip()))
  265. self.interaction(frame, exc_traceback)
  266. # General interaction function
  267. def _cmdloop(self):
  268. while True:
  269. try:
  270. # keyboard interrupts allow for an easy way to cancel
  271. # the current command, so allow them during interactive input
  272. self.allow_kbdint = True
  273. self.cmdloop()
  274. self.allow_kbdint = False
  275. break
  276. except KeyboardInterrupt:
  277. self.message('--KeyboardInterrupt--')
  278. # Called before loop, handles display expressions
  279. def preloop(self):
  280. displaying = self.displaying.get(self.curframe)
  281. if displaying:
  282. for expr, oldvalue in displaying.items():
  283. newvalue = self._getval_except(expr)
  284. # check for identity first; this prevents custom __eq__ to
  285. # be called at every loop, and also prevents instances whose
  286. # fields are changed to be displayed
  287. if newvalue is not oldvalue and newvalue != oldvalue:
  288. displaying[expr] = newvalue
  289. self.message('display %s: %r [old: %r]' %
  290. (expr, newvalue, oldvalue))
  291. def interaction(self, frame, traceback):
  292. # Restore the previous signal handler at the Pdb prompt.
  293. if Pdb._previous_sigint_handler:
  294. signal.signal(signal.SIGINT, Pdb._previous_sigint_handler)
  295. Pdb._previous_sigint_handler = None
  296. if self.setup(frame, traceback):
  297. # no interaction desired at this time (happens if .pdbrc contains
  298. # a command like "continue")
  299. self.forget()
  300. return
  301. self.print_stack_entry(self.stack[self.curindex])
  302. self._cmdloop()
  303. self.forget()
  304. def displayhook(self, obj):
  305. """Custom displayhook for the exec in default(), which prevents
  306. assignment of the _ variable in the builtins.
  307. """
  308. # reproduce the behavior of the standard displayhook, not printing None
  309. if obj is not None:
  310. self.message(repr(obj))
  311. def default(self, line):
  312. if line[:1] == '!': line = line[1:]
  313. locals = self.curframe_locals
  314. globals = self.curframe.f_globals
  315. try:
  316. code = compile(line + '\n', '<stdin>', 'single')
  317. save_stdout = sys.stdout
  318. save_stdin = sys.stdin
  319. save_displayhook = sys.displayhook
  320. try:
  321. sys.stdin = self.stdin
  322. sys.stdout = self.stdout
  323. sys.displayhook = self.displayhook
  324. exec(code, globals, locals)
  325. finally:
  326. sys.stdout = save_stdout
  327. sys.stdin = save_stdin
  328. sys.displayhook = save_displayhook
  329. except:
  330. exc_info = sys.exc_info()[:2]
  331. self.error(traceback.format_exception_only(*exc_info)[-1].strip())
  332. def precmd(self, line):
  333. """Handle alias expansion and ';;' separator."""
  334. if not line.strip():
  335. return line
  336. args = line.split()
  337. while args[0] in self.aliases:
  338. line = self.aliases[args[0]]
  339. ii = 1
  340. for tmpArg in args[1:]:
  341. line = line.replace("%" + str(ii),
  342. tmpArg)
  343. ii += 1
  344. line = line.replace("%*", ' '.join(args[1:]))
  345. args = line.split()
  346. # split into ';;' separated commands
  347. # unless it's an alias command
  348. if args[0] != 'alias':
  349. marker = line.find(';;')
  350. if marker >= 0:
  351. # queue up everything after marker
  352. next = line[marker+2:].lstrip()
  353. self.cmdqueue.append(next)
  354. line = line[:marker].rstrip()
  355. return line
  356. def onecmd(self, line):
  357. """Interpret the argument as though it had been typed in response
  358. to the prompt.
  359. Checks whether this line is typed at the normal prompt or in
  360. a breakpoint command list definition.
  361. """
  362. if not self.commands_defining:
  363. return cmd.Cmd.onecmd(self, line)
  364. else:
  365. return self.handle_command_def(line)
  366. def handle_command_def(self, line):
  367. """Handles one command line during command list definition."""
  368. cmd, arg, line = self.parseline(line)
  369. if not cmd:
  370. return
  371. if cmd == 'silent':
  372. self.commands_silent[self.commands_bnum] = True
  373. return # continue to handle other cmd def in the cmd list
  374. elif cmd == 'end':
  375. self.cmdqueue = []
  376. return 1 # end of cmd list
  377. cmdlist = self.commands[self.commands_bnum]
  378. if arg:
  379. cmdlist.append(cmd+' '+arg)
  380. else:
  381. cmdlist.append(cmd)
  382. # Determine if we must stop
  383. try:
  384. func = getattr(self, 'do_' + cmd)
  385. except AttributeError:
  386. func = self.default
  387. # one of the resuming commands
  388. if func.__name__ in self.commands_resuming:
  389. self.commands_doprompt[self.commands_bnum] = False
  390. self.cmdqueue = []
  391. return 1
  392. return
  393. # interface abstraction functions
  394. def message(self, msg):
  395. print(msg, file=self.stdout)
  396. def error(self, msg):
  397. print('***', msg, file=self.stdout)
  398. # Generic completion functions. Individual complete_foo methods can be
  399. # assigned below to one of these functions.
  400. def _complete_location(self, text, line, begidx, endidx):
  401. # Complete a file/module/function location for break/tbreak/clear.
  402. if line.strip().endswith((':', ',')):
  403. # Here comes a line number or a condition which we can't complete.
  404. return []
  405. # First, try to find matching functions (i.e. expressions).
  406. try:
  407. ret = self._complete_expression(text, line, begidx, endidx)
  408. except Exception:
  409. ret = []
  410. # Then, try to complete file names as well.
  411. globs = glob.glob(text + '*')
  412. for fn in globs:
  413. if os.path.isdir(fn):
  414. ret.append(fn + '/')
  415. elif os.path.isfile(fn) and fn.lower().endswith(('.py', '.pyw')):
  416. ret.append(fn + ':')
  417. return ret
  418. def _complete_bpnumber(self, text, line, begidx, endidx):
  419. # Complete a breakpoint number. (This would be more helpful if we could
  420. # display additional info along with the completions, such as file/line
  421. # of the breakpoint.)
  422. return [str(i) for i, bp in enumerate(bdb.Breakpoint.bpbynumber)
  423. if bp is not None and str(i).startswith(text)]
  424. def _complete_expression(self, text, line, begidx, endidx):
  425. # Complete an arbitrary expression.
  426. if not self.curframe:
  427. return []
  428. # Collect globals and locals. It is usually not really sensible to also
  429. # complete builtins, and they clutter the namespace quite heavily, so we
  430. # leave them out.
  431. ns = self.curframe.f_globals.copy()
  432. ns.update(self.curframe_locals)
  433. if '.' in text:
  434. # Walk an attribute chain up to the last part, similar to what
  435. # rlcompleter does. This will bail if any of the parts are not
  436. # simple attribute access, which is what we want.
  437. dotted = text.split('.')
  438. try:
  439. obj = ns[dotted[0]]
  440. for part in dotted[1:-1]:
  441. obj = getattr(obj, part)
  442. except (KeyError, AttributeError):
  443. return []
  444. prefix = '.'.join(dotted[:-1]) + '.'
  445. return [prefix + n for n in dir(obj) if n.startswith(dotted[-1])]
  446. else:
  447. # Complete a simple name.
  448. return [n for n in ns.keys() if n.startswith(text)]
  449. # Command definitions, called by cmdloop()
  450. # The argument is the remaining string on the command line
  451. # Return true to exit from the command loop
  452. def do_commands(self, arg):
  453. """commands [bpnumber]
  454. (com) ...
  455. (com) end
  456. (Pdb)
  457. Specify a list of commands for breakpoint number bpnumber.
  458. The commands themselves are entered on the following lines.
  459. Type a line containing just 'end' to terminate the commands.
  460. The commands are executed when the breakpoint is hit.
  461. To remove all commands from a breakpoint, type commands and
  462. follow it immediately with end; that is, give no commands.
  463. With no bpnumber argument, commands refers to the last
  464. breakpoint set.
  465. You can use breakpoint commands to start your program up
  466. again. Simply use the continue command, or step, or any other
  467. command that resumes execution.
  468. Specifying any command resuming execution (currently continue,
  469. step, next, return, jump, quit and their abbreviations)
  470. terminates the command list (as if that command was
  471. immediately followed by end). This is because any time you
  472. resume execution (even with a simple next or step), you may
  473. encounter another breakpoint -- which could have its own
  474. command list, leading to ambiguities about which list to
  475. execute.
  476. If you use the 'silent' command in the command list, the usual
  477. message about stopping at a breakpoint is not printed. This
  478. may be desirable for breakpoints that are to print a specific
  479. message and then continue. If none of the other commands
  480. print anything, you will see no sign that the breakpoint was
  481. reached.
  482. """
  483. if not arg:
  484. bnum = len(bdb.Breakpoint.bpbynumber) - 1
  485. else:
  486. try:
  487. bnum = int(arg)
  488. except:
  489. self.error("Usage: commands [bnum]\n ...\n end")
  490. return
  491. self.commands_bnum = bnum
  492. # Save old definitions for the case of a keyboard interrupt.
  493. if bnum in self.commands:
  494. old_command_defs = (self.commands[bnum],
  495. self.commands_doprompt[bnum],
  496. self.commands_silent[bnum])
  497. else:
  498. old_command_defs = None
  499. self.commands[bnum] = []
  500. self.commands_doprompt[bnum] = True
  501. self.commands_silent[bnum] = False
  502. prompt_back = self.prompt
  503. self.prompt = '(com) '
  504. self.commands_defining = True
  505. try:
  506. self.cmdloop()
  507. except KeyboardInterrupt:
  508. # Restore old definitions.
  509. if old_command_defs:
  510. self.commands[bnum] = old_command_defs[0]
  511. self.commands_doprompt[bnum] = old_command_defs[1]
  512. self.commands_silent[bnum] = old_command_defs[2]
  513. else:
  514. del self.commands[bnum]
  515. del self.commands_doprompt[bnum]
  516. del self.commands_silent[bnum]
  517. self.error('command definition aborted, old commands restored')
  518. finally:
  519. self.commands_defining = False
  520. self.prompt = prompt_back
  521. complete_commands = _complete_bpnumber
  522. def do_break(self, arg, temporary = 0):
  523. """b(reak) [ ([filename:]lineno | function) [, condition] ]
  524. Without argument, list all breaks.
  525. With a line number argument, set a break at this line in the
  526. current file. With a function name, set a break at the first
  527. executable line of that function. If a second argument is
  528. present, it is a string specifying an expression which must
  529. evaluate to true before the breakpoint is honored.
  530. The line number may be prefixed with a filename and a colon,
  531. to specify a breakpoint in another file (probably one that
  532. hasn't been loaded yet). The file is searched for on
  533. sys.path; the .py suffix may be omitted.
  534. """
  535. if not arg:
  536. if self.breaks: # There's at least one
  537. self.message("Num Type Disp Enb Where")
  538. for bp in bdb.Breakpoint.bpbynumber:
  539. if bp:
  540. self.message(bp.bpformat())
  541. return
  542. # parse arguments; comma has lowest precedence
  543. # and cannot occur in filename
  544. filename = None
  545. lineno = None
  546. cond = None
  547. comma = arg.find(',')
  548. if comma > 0:
  549. # parse stuff after comma: "condition"
  550. cond = arg[comma+1:].lstrip()
  551. arg = arg[:comma].rstrip()
  552. # parse stuff before comma: [filename:]lineno | function
  553. colon = arg.rfind(':')
  554. funcname = None
  555. if colon >= 0:
  556. filename = arg[:colon].rstrip()
  557. f = self.lookupmodule(filename)
  558. if not f:
  559. self.error('%r not found from sys.path' % filename)
  560. return
  561. else:
  562. filename = f
  563. arg = arg[colon+1:].lstrip()
  564. try:
  565. lineno = int(arg)
  566. except ValueError:
  567. self.error('Bad lineno: %s' % arg)
  568. return
  569. else:
  570. # no colon; can be lineno or function
  571. try:
  572. lineno = int(arg)
  573. except ValueError:
  574. try:
  575. func = eval(arg,
  576. self.curframe.f_globals,
  577. self.curframe_locals)
  578. except:
  579. func = arg
  580. try:
  581. if hasattr(func, '__func__'):
  582. func = func.__func__
  583. code = func.__code__
  584. #use co_name to identify the bkpt (function names
  585. #could be aliased, but co_name is invariant)
  586. funcname = code.co_name
  587. lineno = code.co_firstlineno
  588. filename = code.co_filename
  589. except:
  590. # last thing to try
  591. (ok, filename, ln) = self.lineinfo(arg)
  592. if not ok:
  593. self.error('The specified object %r is not a function '
  594. 'or was not found along sys.path.' % arg)
  595. return
  596. funcname = ok # ok contains a function name
  597. lineno = int(ln)
  598. if not filename:
  599. filename = self.defaultFile()
  600. # Check for reasonable breakpoint
  601. line = self.checkline(filename, lineno)
  602. if line:
  603. # now set the break point
  604. err = self.set_break(filename, line, temporary, cond, funcname)
  605. if err:
  606. self.error(err)
  607. else:
  608. bp = self.get_breaks(filename, line)[-1]
  609. self.message("Breakpoint %d at %s:%d" %
  610. (bp.number, bp.file, bp.line))
  611. # To be overridden in derived debuggers
  612. def defaultFile(self):
  613. """Produce a reasonable default."""
  614. filename = self.curframe.f_code.co_filename
  615. if filename == '<string>' and self.mainpyfile:
  616. filename = self.mainpyfile
  617. return filename
  618. do_b = do_break
  619. complete_break = _complete_location
  620. complete_b = _complete_location
  621. def do_tbreak(self, arg):
  622. """tbreak [ ([filename:]lineno | function) [, condition] ]
  623. Same arguments as break, but sets a temporary breakpoint: it
  624. is automatically deleted when first hit.
  625. """
  626. self.do_break(arg, 1)
  627. complete_tbreak = _complete_location
  628. def lineinfo(self, identifier):
  629. failed = (None, None, None)
  630. # Input is identifier, may be in single quotes
  631. idstring = identifier.split("'")
  632. if len(idstring) == 1:
  633. # not in single quotes
  634. id = idstring[0].strip()
  635. elif len(idstring) == 3:
  636. # quoted
  637. id = idstring[1].strip()
  638. else:
  639. return failed
  640. if id == '': return failed
  641. parts = id.split('.')
  642. # Protection for derived debuggers
  643. if parts[0] == 'self':
  644. del parts[0]
  645. if len(parts) == 0:
  646. return failed
  647. # Best first guess at file to look at
  648. fname = self.defaultFile()
  649. if len(parts) == 1:
  650. item = parts[0]
  651. else:
  652. # More than one part.
  653. # First is module, second is method/class
  654. f = self.lookupmodule(parts[0])
  655. if f:
  656. fname = f
  657. item = parts[1]
  658. answer = find_function(item, fname)
  659. return answer or failed
  660. def checkline(self, filename, lineno):
  661. """Check whether specified line seems to be executable.
  662. Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
  663. line or EOF). Warning: testing is not comprehensive.
  664. """
  665. # this method should be callable before starting debugging, so default
  666. # to "no globals" if there is no current frame
  667. globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
  668. line = linecache.getline(filename, lineno, globs)
  669. if not line:
  670. self.message('End of file')
  671. return 0
  672. line = line.strip()
  673. # Don't allow setting breakpoint at a blank line
  674. if (not line or (line[0] == '#') or
  675. (line[:3] == '"""') or line[:3] == "'''"):
  676. self.error('Blank or comment')
  677. return 0
  678. return lineno
  679. def do_enable(self, arg):
  680. """enable bpnumber [bpnumber ...]
  681. Enables the breakpoints given as a space separated list of
  682. breakpoint numbers.
  683. """
  684. args = arg.split()
  685. for i in args:
  686. try:
  687. bp = self.get_bpbynumber(i)
  688. except ValueError as err:
  689. self.error(err)
  690. else:
  691. bp.enable()
  692. self.message('Enabled %s' % bp)
  693. complete_enable = _complete_bpnumber
  694. def do_disable(self, arg):
  695. """disable bpnumber [bpnumber ...]
  696. Disables the breakpoints given as a space separated list of
  697. breakpoint numbers. Disabling a breakpoint means it cannot
  698. cause the program to stop execution, but unlike clearing a
  699. breakpoint, it remains in the list of breakpoints and can be
  700. (re-)enabled.
  701. """
  702. args = arg.split()
  703. for i in args:
  704. try:
  705. bp = self.get_bpbynumber(i)
  706. except ValueError as err:
  707. self.error(err)
  708. else:
  709. bp.disable()
  710. self.message('Disabled %s' % bp)
  711. complete_disable = _complete_bpnumber
  712. def do_condition(self, arg):
  713. """condition bpnumber [condition]
  714. Set a new condition for the breakpoint, an expression which
  715. must evaluate to true before the breakpoint is honored. If
  716. condition is absent, any existing condition is removed; i.e.,
  717. the breakpoint is made unconditional.
  718. """
  719. args = arg.split(' ', 1)
  720. try:
  721. cond = args[1]
  722. except IndexError:
  723. cond = None
  724. try:
  725. bp = self.get_bpbynumber(args[0].strip())
  726. except IndexError:
  727. self.error('Breakpoint number expected')
  728. except ValueError as err:
  729. self.error(err)
  730. else:
  731. bp.cond = cond
  732. if not cond:
  733. self.message('Breakpoint %d is now unconditional.' % bp.number)
  734. else:
  735. self.message('New condition set for breakpoint %d.' % bp.number)
  736. complete_condition = _complete_bpnumber
  737. def do_ignore(self, arg):
  738. """ignore bpnumber [count]
  739. Set the ignore count for the given breakpoint number. If
  740. count is omitted, the ignore count is set to 0. A breakpoint
  741. becomes active when the ignore count is zero. When non-zero,
  742. the count is decremented each time the breakpoint is reached
  743. and the breakpoint is not disabled and any associated
  744. condition evaluates to true.
  745. """
  746. args = arg.split()
  747. try:
  748. count = int(args[1].strip())
  749. except:
  750. count = 0
  751. try:
  752. bp = self.get_bpbynumber(args[0].strip())
  753. except IndexError:
  754. self.error('Breakpoint number expected')
  755. except ValueError as err:
  756. self.error(err)
  757. else:
  758. bp.ignore = count
  759. if count > 0:
  760. if count > 1:
  761. countstr = '%d crossings' % count
  762. else:
  763. countstr = '1 crossing'
  764. self.message('Will ignore next %s of breakpoint %d.' %
  765. (countstr, bp.number))
  766. else:
  767. self.message('Will stop next time breakpoint %d is reached.'
  768. % bp.number)
  769. complete_ignore = _complete_bpnumber
  770. def do_clear(self, arg):
  771. """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
  772. With a space separated list of breakpoint numbers, clear
  773. those breakpoints. Without argument, clear all breaks (but
  774. first ask confirmation). With a filename:lineno argument,
  775. clear all breaks at that line in that file.
  776. """
  777. if not arg:
  778. try:
  779. reply = input('Clear all breaks? ')
  780. except EOFError:
  781. reply = 'no'
  782. reply = reply.strip().lower()
  783. if reply in ('y', 'yes'):
  784. bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
  785. self.clear_all_breaks()
  786. for bp in bplist:
  787. self.message('Deleted %s' % bp)
  788. return
  789. if ':' in arg:
  790. # Make sure it works for "clear C:\foo\bar.py:12"
  791. i = arg.rfind(':')
  792. filename = arg[:i]
  793. arg = arg[i+1:]
  794. try:
  795. lineno = int(arg)
  796. except ValueError:
  797. err = "Invalid line number (%s)" % arg
  798. else:
  799. bplist = self.get_breaks(filename, lineno)
  800. err = self.clear_break(filename, lineno)
  801. if err:
  802. self.error(err)
  803. else:
  804. for bp in bplist:
  805. self.message('Deleted %s' % bp)
  806. return
  807. numberlist = arg.split()
  808. for i in numberlist:
  809. try:
  810. bp = self.get_bpbynumber(i)
  811. except ValueError as err:
  812. self.error(err)
  813. else:
  814. self.clear_bpbynumber(i)
  815. self.message('Deleted %s' % bp)
  816. do_cl = do_clear # 'c' is already an abbreviation for 'continue'
  817. complete_clear = _complete_location
  818. complete_cl = _complete_location
  819. def do_where(self, arg):
  820. """w(here)
  821. Print a stack trace, with the most recent frame at the bottom.
  822. An arrow indicates the "current frame", which determines the
  823. context of most commands. 'bt' is an alias for this command.
  824. """
  825. self.print_stack_trace()
  826. do_w = do_where
  827. do_bt = do_where
  828. def _select_frame(self, number):
  829. assert 0 <= number < len(self.stack)
  830. self.curindex = number
  831. self.curframe = self.stack[self.curindex][0]
  832. self.curframe_locals = self.curframe.f_locals
  833. self.print_stack_entry(self.stack[self.curindex])
  834. self.lineno = None
  835. def do_up(self, arg):
  836. """u(p) [count]
  837. Move the current frame count (default one) levels up in the
  838. stack trace (to an older frame).
  839. """
  840. if self.curindex == 0:
  841. self.error('Oldest frame')
  842. return
  843. try:
  844. count = int(arg or 1)
  845. except ValueError:
  846. self.error('Invalid frame count (%s)' % arg)
  847. return
  848. if count < 0:
  849. newframe = 0
  850. else:
  851. newframe = max(0, self.curindex - count)
  852. self._select_frame(newframe)
  853. do_u = do_up
  854. def do_down(self, arg):
  855. """d(own) [count]
  856. Move the current frame count (default one) levels down in the
  857. stack trace (to a newer frame).
  858. """
  859. if self.curindex + 1 == len(self.stack):
  860. self.error('Newest frame')
  861. return
  862. try:
  863. count = int(arg or 1)
  864. except ValueError:
  865. self.error('Invalid frame count (%s)' % arg)
  866. return
  867. if count < 0:
  868. newframe = len(self.stack) - 1
  869. else:
  870. newframe = min(len(self.stack) - 1, self.curindex + count)
  871. self._select_frame(newframe)
  872. do_d = do_down
  873. def do_until(self, arg):
  874. """unt(il) [lineno]
  875. Without argument, continue execution until the line with a
  876. number greater than the current one is reached. With a line
  877. number, continue execution until a line with a number greater
  878. or equal to that is reached. In both cases, also stop when
  879. the current frame returns.
  880. """
  881. if arg:
  882. try:
  883. lineno = int(arg)
  884. except ValueError:
  885. self.error('Error in argument: %r' % arg)
  886. return
  887. if lineno <= self.curframe.f_lineno:
  888. self.error('"until" line number is smaller than current '
  889. 'line number')
  890. return
  891. else:
  892. lineno = None
  893. self.set_until(self.curframe, lineno)
  894. return 1
  895. do_unt = do_until
  896. def do_step(self, arg):
  897. """s(tep)
  898. Execute the current line, stop at the first possible occasion
  899. (either in a function that is called or in the current
  900. function).
  901. """
  902. self.set_step()
  903. return 1
  904. do_s = do_step
  905. def do_next(self, arg):
  906. """n(ext)
  907. Continue execution until the next line in the current function
  908. is reached or it returns.
  909. """
  910. self.set_next(self.curframe)
  911. return 1
  912. do_n = do_next
  913. def do_run(self, arg):
  914. """run [args...]
  915. Restart the debugged python program. If a string is supplied
  916. it is split with "shlex", and the result is used as the new
  917. sys.argv. History, breakpoints, actions and debugger options
  918. are preserved. "restart" is an alias for "run".
  919. """
  920. if arg:
  921. import shlex
  922. argv0 = sys.argv[0:1]
  923. sys.argv = shlex.split(arg)
  924. sys.argv[:0] = argv0
  925. # this is caught in the main debugger loop
  926. raise Restart
  927. do_restart = do_run
  928. def do_return(self, arg):
  929. """r(eturn)
  930. Continue execution until the current function returns.
  931. """
  932. self.set_return(self.curframe)
  933. return 1
  934. do_r = do_return
  935. def do_continue(self, arg):
  936. """c(ont(inue))
  937. Continue execution, only stop when a breakpoint is encountered.
  938. """
  939. if not self.nosigint:
  940. try:
  941. Pdb._previous_sigint_handler = \
  942. signal.signal(signal.SIGINT, self.sigint_handler)
  943. except ValueError:
  944. # ValueError happens when do_continue() is invoked from
  945. # a non-main thread in which case we just continue without
  946. # SIGINT set. Would printing a message here (once) make
  947. # sense?
  948. pass
  949. self.set_continue()
  950. return 1
  951. do_c = do_cont = do_continue
  952. def do_jump(self, arg):
  953. """j(ump) lineno
  954. Set the next line that will be executed. Only available in
  955. the bottom-most frame. This lets you jump back and execute
  956. code again, or jump forward to skip code that you don't want
  957. to run.
  958. It should be noted that not all jumps are allowed -- for
  959. instance it is not possible to jump into the middle of a
  960. for loop or out of a finally clause.
  961. """
  962. if self.curindex + 1 != len(self.stack):
  963. self.error('You can only jump within the bottom frame')
  964. return
  965. try:
  966. arg = int(arg)
  967. except ValueError:
  968. self.error("The 'jump' command requires a line number")
  969. else:
  970. try:
  971. # Do the jump, fix up our copy of the stack, and display the
  972. # new position
  973. self.curframe.f_lineno = arg
  974. self.stack[self.curindex] = self.stack[self.curindex][0], arg
  975. self.print_stack_entry(self.stack[self.curindex])
  976. except ValueError as e:
  977. self.error('Jump failed: %s' % e)
  978. do_j = do_jump
  979. def do_debug(self, arg):
  980. """debug code
  981. Enter a recursive debugger that steps through the code
  982. argument (which is an arbitrary expression or statement to be
  983. executed in the current environment).
  984. """
  985. sys.settrace(None)
  986. globals = self.curframe.f_globals
  987. locals = self.curframe_locals
  988. p = Pdb(self.completekey, self.stdin, self.stdout)
  989. p.prompt = "(%s) " % self.prompt.strip()
  990. self.message("ENTERING RECURSIVE DEBUGGER")
  991. try:
  992. sys.call_tracing(p.run, (arg, globals, locals))
  993. except Exception:
  994. exc_info = sys.exc_info()[:2]
  995. self.error(traceback.format_exception_only(*exc_info)[-1].strip())
  996. self.message("LEAVING RECURSIVE DEBUGGER")
  997. sys.settrace(self.trace_dispatch)
  998. self.lastcmd = p.lastcmd
  999. complete_debug = _complete_expression
  1000. def do_quit(self, arg):
  1001. """q(uit)\nexit
  1002. Quit from the debugger. The program being executed is aborted.
  1003. """
  1004. self._user_requested_quit = True
  1005. self.set_quit()
  1006. return 1
  1007. do_q = do_quit
  1008. do_exit = do_quit
  1009. def do_EOF(self, arg):
  1010. """EOF
  1011. Handles the receipt of EOF as a command.
  1012. """
  1013. self.message('')
  1014. self._user_requested_quit = True
  1015. self.set_quit()
  1016. return 1
  1017. def do_args(self, arg):
  1018. """a(rgs)
  1019. Print the argument list of the current function.
  1020. """
  1021. co = self.curframe.f_code
  1022. dict = self.curframe_locals
  1023. n = co.co_argcount + co.co_kwonlyargcount
  1024. if co.co_flags & inspect.CO_VARARGS: n = n+1
  1025. if co.co_flags & inspect.CO_VARKEYWORDS: n = n+1
  1026. for i in range(n):
  1027. name = co.co_varnames[i]
  1028. if name in dict:
  1029. self.message('%s = %r' % (name, dict[name]))
  1030. else:
  1031. self.message('%s = *** undefined ***' % (name,))
  1032. do_a = do_args
  1033. def do_retval(self, arg):
  1034. """retval
  1035. Print the return value for the last return of a function.
  1036. """
  1037. if '__return__' in self.curframe_locals:
  1038. self.message(repr(self.curframe_locals['__return__']))
  1039. else:
  1040. self.error('Not yet returned!')
  1041. do_rv = do_retval
  1042. def _getval(self, arg):
  1043. try:
  1044. return eval(arg, self.curframe.f_globals, self.curframe_locals)
  1045. except:
  1046. exc_info = sys.exc_info()[:2]
  1047. self.error(traceback.format_exception_only(*exc_info)[-1].strip())
  1048. raise
  1049. def _getval_except(self, arg, frame=None):
  1050. try:
  1051. if frame is None:
  1052. return eval(arg, self.curframe.f_globals, self.curframe_locals)
  1053. else:
  1054. return eval(arg, frame.f_globals, frame.f_locals)
  1055. except:
  1056. exc_info = sys.exc_info()[:2]
  1057. err = traceback.format_exception_only(*exc_info)[-1].strip()
  1058. return _rstr('** raised %s **' % err)
  1059. def do_p(self, arg):
  1060. """p expression
  1061. Print the value of the expression.
  1062. """
  1063. try:
  1064. self.message(repr(self._getval(arg)))
  1065. except:
  1066. pass
  1067. def do_pp(self, arg):
  1068. """pp expression
  1069. Pretty-print the value of the expression.
  1070. """
  1071. try:
  1072. self.message(pprint.pformat(self._getval(arg)))
  1073. except:
  1074. pass
  1075. complete_print = _complete_expression
  1076. complete_p = _complete_expression
  1077. complete_pp = _complete_expression
  1078. def do_list(self, arg):
  1079. """l(ist) [first [,last] | .]
  1080. List source code for the current file. Without arguments,
  1081. list 11 lines around the current line or continue the previous
  1082. listing. With . as argument, list 11 lines around the current
  1083. line. With one argument, list 11 lines starting at that line.
  1084. With two arguments, list the given range; if the second
  1085. argument is less than the first, it is a count.
  1086. The current line in the current frame is indicated by "->".
  1087. If an exception is being debugged, the line where the
  1088. exception was originally raised or propagated is indicated by
  1089. ">>", if it differs from the current line.
  1090. """
  1091. self.lastcmd = 'list'
  1092. last = None
  1093. if arg and arg != '.':
  1094. try:
  1095. if ',' in arg:
  1096. first, last = arg.split(',')
  1097. first = int(first.strip())
  1098. last = int(last.strip())
  1099. if last < first:
  1100. # assume it's a count
  1101. last = first + last
  1102. else:
  1103. first = int(arg.strip())
  1104. first = max(1, first - 5)
  1105. except ValueError:
  1106. self.error('Error in argument: %r' % arg)
  1107. return
  1108. elif self.lineno is None or arg == '.':
  1109. first = max(1, self.curframe.f_lineno - 5)
  1110. else:
  1111. first = self.lineno + 1
  1112. if last is None:
  1113. last = first + 10
  1114. filename = self.curframe.f_code.co_filename
  1115. breaklist = self.get_file_breaks(filename)
  1116. try:
  1117. lines = linecache.getlines(filename, self.curframe.f_globals)
  1118. self._print_lines(lines[first-1:last], first, breaklist,
  1119. self.curframe)
  1120. self.lineno = min(last, len(lines))
  1121. if len(lines) < last:
  1122. self.message('[EOF]')
  1123. except KeyboardInterrupt:
  1124. pass
  1125. do_l = do_list
  1126. def do_longlist(self, arg):
  1127. """longlist | ll
  1128. List the whole source code for the current function or frame.
  1129. """
  1130. filename = self.curframe.f_code.co_filename
  1131. breaklist = self.get_file_breaks(filename)
  1132. try:
  1133. lines, lineno = getsourcelines(self.curframe)
  1134. except OSError as err:
  1135. self.error(err)
  1136. return
  1137. self._print_lines(lines, lineno, breaklist, self.curframe)
  1138. do_ll = do_longlist
  1139. def do_source(self, arg):
  1140. """source expression
  1141. Try to get source code for the given object and display it.
  1142. """
  1143. try:
  1144. obj = self._getval(arg)
  1145. except:
  1146. return
  1147. try:
  1148. lines, lineno = getsourcelines(obj)
  1149. except (OSError, TypeError) as err:
  1150. self.error(err)
  1151. return
  1152. self._print_lines(lines, lineno)
  1153. complete_source = _complete_expression
  1154. def _print_lines(self, lines, start, breaks=(), frame=None):
  1155. """Print a range of lines."""
  1156. if frame:
  1157. current_lineno = frame.f_lineno
  1158. exc_lineno = self.tb_lineno.get(frame, -1)
  1159. else:
  1160. current_lineno = exc_lineno = -1
  1161. for lineno, line in enumerate(lines, start):
  1162. s = str(lineno).rjust(3)
  1163. if len(s) < 4:
  1164. s += ' '
  1165. if lineno in breaks:
  1166. s += 'B'
  1167. else:
  1168. s += ' '
  1169. if lineno == current_lineno:
  1170. s += '->'
  1171. elif lineno == exc_lineno:
  1172. s += '>>'
  1173. self.message(s + '\t' + line.rstrip())
  1174. def do_whatis(self, arg):
  1175. """whatis arg
  1176. Print the type of the argument.
  1177. """
  1178. try:
  1179. value = self._getval(arg)
  1180. except:
  1181. # _getval() already printed the error
  1182. return
  1183. code = None
  1184. # Is it a function?
  1185. try:
  1186. code = value.__code__
  1187. except Exception:
  1188. pass
  1189. if code:
  1190. self.message('Function %s' % code.co_name)
  1191. return
  1192. # Is it an instance method?
  1193. try:
  1194. code = value.__func__.__code__
  1195. except Exception:
  1196. pass
  1197. if code:
  1198. self.message('Method %s' % code.co_name)
  1199. return
  1200. # Is it a class?
  1201. if value.__class__ is type:
  1202. self.message('Class %s.%s' % (value.__module__, value.__qualname__))
  1203. return
  1204. # None of the above...
  1205. self.message(type(value))
  1206. complete_whatis = _complete_expression
  1207. def do_display(self, arg):
  1208. """display [expression]
  1209. Display the value of the expression if it changed, each time execution
  1210. stops in the current frame.
  1211. Without expression, list all display expressions for the current frame.
  1212. """
  1213. if not arg:
  1214. self.message('Currently displaying:')
  1215. for item in self.displaying.get(self.curframe, {}).items():
  1216. self.message('%s: %r' % item)
  1217. else:
  1218. val = self._getval_except(arg)
  1219. self.displaying.setdefault(self.curframe, {})[arg] = val
  1220. self.message('display %s: %r' % (arg, val))
  1221. complete_display = _complete_expression
  1222. def do_undisplay(self, arg):
  1223. """undisplay [expression]
  1224. Do not display the expression any more in the current frame.
  1225. Without expression, clear all display expressions for the current frame.
  1226. """
  1227. if arg:
  1228. try:
  1229. del self.displaying.get(self.curframe, {})[arg]
  1230. except KeyError:
  1231. self.error('not displaying %s' % arg)
  1232. else:
  1233. self.displaying.pop(self.curframe, None)
  1234. def complete_undisplay(self, text, line, begidx, endidx):
  1235. return [e for e in self.displaying.get(self.curframe, {})
  1236. if e.startswith(text)]
  1237. def do_interact(self, arg):
  1238. """interact
  1239. Start an interactive interpreter whose global namespace
  1240. contains all the (global and local) names found in the current scope.
  1241. """
  1242. ns = self.curframe.f_globals.copy()
  1243. ns.update(self.curframe_locals)
  1244. code.interact("*interactive*", local=ns)
  1245. def do_alias(self, arg):
  1246. """alias [name [command [parameter parameter ...] ]]
  1247. Create an alias called 'name' that executes 'command'. The
  1248. command must *not* be enclosed in quotes. Replaceable
  1249. parameters can be indicated by %1, %2, and so on, while %* is
  1250. replaced by all the parameters. If no command is given, the
  1251. current alias for name is shown. If no name is given, all
  1252. aliases are listed.
  1253. Aliases may be nested and can contain anything that can be
  1254. legally typed at the pdb prompt. Note! You *can* override
  1255. internal pdb commands with aliases! Those internal commands
  1256. are then hidden until the alias is removed. Aliasing is
  1257. recursively applied to the first word of the command line; all
  1258. other words in the line are left alone.
  1259. As an example, here are two useful aliases (especially when
  1260. placed in the .pdbrc file):
  1261. # Print instance variables (usage "pi classInst")
  1262. alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])
  1263. # Print instance variables in self
  1264. alias ps pi self
  1265. """
  1266. args = arg.split()
  1267. if len(args) == 0:
  1268. keys = sorted(self.aliases.keys())
  1269. for alias in keys:
  1270. self.message("%s = %s" % (alias, self.aliases[alias]))
  1271. return
  1272. if args[0] in self.aliases and len(args) == 1:
  1273. self.message("%s = %s" % (args[0], self.aliases[args[0]]))
  1274. else:
  1275. self.aliases[args[0]] = ' '.join(args[1:])
  1276. def do_unalias(self, arg):
  1277. """unalias name
  1278. Delete the specified alias.
  1279. """
  1280. args = arg.split()
  1281. if len(args) == 0: return
  1282. if args[0] in self.aliases:
  1283. del self.aliases[args[0]]
  1284. def complete_unalias(self, text, line, begidx, endidx):
  1285. return [a for a in self.aliases if a.startswith(text)]
  1286. # List of all the commands making the program resume execution.
  1287. commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
  1288. 'do_quit', 'do_jump']
  1289. # Print a traceback starting at the top stack frame.
  1290. # The most recently entered frame is printed last;
  1291. # this is different from dbx and gdb, but consistent with
  1292. # the Python interpreter's stack trace.
  1293. # It is also consistent with the up/down commands (which are
  1294. # compatible with dbx and gdb: up moves towards 'main()'
  1295. # and down moves towards the most recent stack frame).
  1296. def print_stack_trace(self):
  1297. try:
  1298. for frame_lineno in self.stack:
  1299. self.print_stack_entry(frame_lineno)
  1300. except KeyboardInterrupt:
  1301. pass
  1302. def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
  1303. frame, lineno = frame_lineno
  1304. if frame is self.curframe:
  1305. prefix = '> '
  1306. else:
  1307. prefix = ' '
  1308. self.message(prefix +
  1309. self.format_stack_entry(frame_lineno, prompt_prefix))
  1310. # Provide help
  1311. def do_help(self, arg):
  1312. """h(elp)
  1313. Without argument, print the list of available commands.
  1314. With a command name as argument, print help about that command.
  1315. "help pdb" shows the full pdb documentation.
  1316. "help exec" gives help on the ! command.
  1317. """
  1318. if not arg:
  1319. return cmd.Cmd.do_help(self, arg)
  1320. try:
  1321. try:
  1322. topic = getattr(self, 'help_' + arg)
  1323. return topic()
  1324. except AttributeError:
  1325. command = getattr(self, 'do_' + arg)
  1326. except AttributeError:
  1327. self.error('No help for %r' % arg)
  1328. else:
  1329. if sys.flags.optimize >= 2:
  1330. self.error('No help for %r; please do not run Python with -OO '
  1331. 'if you need command help' % arg)
  1332. return
  1333. self.message(command.__doc__.rstrip())
  1334. do_h = do_help
  1335. def help_exec(self):
  1336. """(!) statement
  1337. Execute the (one-line) statement in the context of the current
  1338. stack frame. The exclamation point can be omitted unless the
  1339. first word of the statement resembles a debugger command. To
  1340. assign to a global variable you must always prefix the command
  1341. with a 'global' command, e.g.:
  1342. (Pdb) global list_options; list_options = ['-l']
  1343. (Pdb)
  1344. """
  1345. self.message((self.help_exec.__doc__ or '').strip())
  1346. def help_pdb(self):
  1347. help()
  1348. # other helper functions
  1349. def lookupmodule(self, filename):
  1350. """Helper function for break/clear parsing -- may be overridden.
  1351. lookupmodule() translates (possibly incomplete) file or module name
  1352. into an absolute file name.
  1353. """
  1354. if os.path.isabs(filename) and os.path.exists(filename):
  1355. return filename
  1356. f = os.path.join(sys.path[0], filename)
  1357. if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
  1358. return f
  1359. root, ext = os.path.splitext(filename)
  1360. if ext == '':
  1361. filename = filename + '.py'
  1362. if os.path.isabs(filename):
  1363. return filename
  1364. for dirname in sys.path:
  1365. while os.path.islink(dirname):
  1366. dirname = os.readlink(dirname)
  1367. fullname = os.path.join(dirname, filename)
  1368. if os.path.exists(fullname):
  1369. return fullname
  1370. return None
  1371. def _runmodule(self, module_name):
  1372. self._wait_for_mainpyfile = True
  1373. self._user_requested_quit = False
  1374. import runpy
  1375. mod_name, mod_spec, code = runpy._get_module_details(module_name)
  1376. self.mainpyfile = self.canonic(code.co_filename)
  1377. import __main__
  1378. __main__.__dict__.clear()
  1379. __main__.__dict__.update({
  1380. "__name__": "__main__",
  1381. "__file__": self.mainpyfile,
  1382. "__package__": mod_spec.parent,
  1383. "__loader__": mod_spec.loader,
  1384. "__spec__": mod_spec,
  1385. "__builtins__": __builtins__,
  1386. })
  1387. self.run(code)
  1388. def _runscript(self, filename):
  1389. # The script has to run in __main__ namespace (or imports from
  1390. # __main__ will break).
  1391. #
  1392. # So we clear up the __main__ and set several special variables
  1393. # (this gets rid of pdb's globals and cleans old variables on restarts).
  1394. import __main__
  1395. __main__.__dict__.clear()
  1396. __main__.__dict__.update({"__name__" : "__main__",
  1397. "__file__" : filename,
  1398. "__builtins__": __builtins__,
  1399. })
  1400. # When bdb sets tracing, a number of call and line events happens
  1401. # BEFORE debugger even reaches user's code (and the exact sequence of
  1402. # events depends on python version). So we take special measures to
  1403. # avoid stopping before we reach the main script (see user_line and
  1404. # user_call for details).
  1405. self._wait_for_mainpyfile = True
  1406. self.mainpyfile = self.canonic(filename)
  1407. self._user_requested_quit = False
  1408. with open(filename, "rb") as fp:
  1409. statement = "exec(compile(%r, %r, 'exec'))" % \
  1410. (fp.read(), self.mainpyfile)
  1411. self.run(statement)
  1412. # Collect all command help into docstring, if not run with -OO
  1413. if __doc__ is not None:
  1414. # unfortunately we can't guess this order from the class definition
  1415. _help_order = [
  1416. 'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
  1417. 'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
  1418. 'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
  1419. 'args', 'p', 'pp', 'whatis', 'source', 'display', 'undisplay',
  1420. 'interact', 'alias', 'unalias', 'debug', 'quit',
  1421. ]
  1422. for _command in _help_order:
  1423. __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n'
  1424. __doc__ += Pdb.help_exec.__doc__
  1425. del _help_order, _command
  1426. # Simplified interface
  1427. def run(statement, globals=None, locals=None):
  1428. Pdb().run(statement, globals, locals)
  1429. def runeval(expression, globals=None, locals=None):
  1430. return Pdb().runeval(expression, globals, locals)
  1431. def runctx(statement, globals, locals):
  1432. # B/W compatibility
  1433. run(statement, globals, locals)
  1434. def runcall(*args, **kwds):
  1435. return Pdb().runcall(*args, **kwds)
  1436. def set_trace(*, header=None):
  1437. pdb = Pdb()
  1438. if header is not None:
  1439. pdb.message(header)
  1440. pdb.set_trace(sys._getframe().f_back)
  1441. # Post-Mortem interface
  1442. def post_mortem(t=None):
  1443. # handling the default
  1444. if t is None:
  1445. # sys.exc_info() returns (type, value, traceback) if an exception is
  1446. # being handled, otherwise it returns None
  1447. t = sys.exc_info()[2]
  1448. if t is None:
  1449. raise ValueError("A valid traceback must be passed if no "
  1450. "exception is being handled")
  1451. p = Pdb()
  1452. p.reset()
  1453. p.interaction(None, t)
  1454. def pm():
  1455. post_mortem(sys.last_traceback)
  1456. # Main program for testing
  1457. TESTCMD = 'import x; x.main()'
  1458. def test():
  1459. run(TESTCMD)
  1460. # print help
  1461. def help():
  1462. import pydoc
  1463. pydoc.pager(__doc__)
  1464. _usage = """\
  1465. usage: pdb.py [-c command] ... [-m module | pyfile] [arg] ...
  1466. Debug the Python program given by pyfile. Alternatively,
  1467. an executable module or package to debug can be specified using
  1468. the -m switch.
  1469. Initial commands are read from .pdbrc files in your home directory
  1470. and in the current directory, if they exist. Commands supplied with
  1471. -c are executed after commands from .pdbrc files.
  1472. To let the script run until an exception occurs, use "-c continue".
  1473. To let the script run up to a given line X in the debugged file, use
  1474. "-c 'until X'"."""
  1475. def main():
  1476. import getopt
  1477. opts, args = getopt.getopt(sys.argv[1:], 'mhc:', ['help', 'command='])
  1478. if not args:
  1479. print(_usage)
  1480. sys.exit(2)
  1481. commands = []
  1482. run_as_module = False
  1483. for opt, optarg in opts:
  1484. if opt in ['-h', '--help']:
  1485. print(_usage)
  1486. sys.exit()
  1487. elif opt in ['-c', '--command']:
  1488. commands.append(optarg)
  1489. elif opt in ['-m']:
  1490. run_as_module = True
  1491. mainpyfile = args[0] # Get script filename
  1492. if not run_as_module and not os.path.exists(mainpyfile):
  1493. print('Error:', mainpyfile, 'does not exist')
  1494. sys.exit(1)
  1495. sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
  1496. # Replace pdb's dir with script's dir in front of module search path.
  1497. if not run_as_module:
  1498. sys.path[0] = os.path.dirname(mainpyfile)
  1499. # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
  1500. # modified by the script being debugged. It's a bad idea when it was
  1501. # changed by the user from the command line. There is a "restart" command
  1502. # which allows explicit specification of command line arguments.
  1503. pdb = Pdb()
  1504. pdb.rcLines.extend(commands)
  1505. while True:
  1506. try:
  1507. if run_as_module:
  1508. pdb._runmodule(mainpyfile)
  1509. else:
  1510. pdb._runscript(mainpyfile)
  1511. if pdb._user_requested_quit:
  1512. break
  1513. print("The program finished and will be restarted")
  1514. except Restart:
  1515. print("Restarting", mainpyfile, "with arguments:")
  1516. print("\t" + " ".join(args))
  1517. except SystemExit:
  1518. # In most cases SystemExit does not warrant a post-mortem session.
  1519. print("The program exited via sys.exit(). Exit status:", end=' ')
  1520. print(sys.exc_info()[1])
  1521. except SyntaxError:
  1522. traceback.print_exc()
  1523. sys.exit(1)
  1524. except:
  1525. traceback.print_exc()
  1526. print("Uncaught exception. Entering post mortem debugging")
  1527. print("Running 'cont' or 'step' will restart the program")
  1528. t = sys.exc_info()[2]
  1529. pdb.interaction(None, t)
  1530. print("Post mortem debugger finished. The " + mainpyfile +
  1531. " will be restarted")
  1532. # When invoked as main program, invoke the debugger on a script
  1533. if __name__ == '__main__':
  1534. import pdb
  1535. pdb.main()