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