pdb.py 62 KB

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