pdb.py 61 KB

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