pdb.py 69 KB

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