pdb.py 68 KB

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