pdb.py 69 KB

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