pdb.py 67 KB

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