debugger.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import asyncio
  2. import os
  3. import sys
  4. from IPython.core.debugger import Pdb
  5. from IPython.core.completer import IPCompleter
  6. from .ptutils import IPythonPTCompleter
  7. from .shortcuts import create_ipython_shortcuts
  8. from . import embed
  9. from pathlib import Path
  10. from pygments.token import Token
  11. from prompt_toolkit.application import create_app_session
  12. from prompt_toolkit.shortcuts.prompt import PromptSession
  13. from prompt_toolkit.enums import EditingMode
  14. from prompt_toolkit.formatted_text import PygmentsTokens
  15. from prompt_toolkit.history import InMemoryHistory, FileHistory
  16. from concurrent.futures import ThreadPoolExecutor
  17. from prompt_toolkit import __version__ as ptk_version
  18. PTK3 = ptk_version.startswith('3.')
  19. # we want to avoid ptk as much as possible when using subprocesses
  20. # as it uses cursor positioning requests, deletes color ....
  21. _use_simple_prompt = "IPY_TEST_SIMPLE_PROMPT" in os.environ
  22. class TerminalPdb(Pdb):
  23. """Standalone IPython debugger."""
  24. def __init__(self, *args, pt_session_options=None, **kwargs):
  25. Pdb.__init__(self, *args, **kwargs)
  26. self._ptcomp = None
  27. self.pt_init(pt_session_options)
  28. self.thread_executor = ThreadPoolExecutor(1)
  29. def pt_init(self, pt_session_options=None):
  30. """Initialize the prompt session and the prompt loop
  31. and store them in self.pt_app and self.pt_loop.
  32. Additional keyword arguments for the PromptSession class
  33. can be specified in pt_session_options.
  34. """
  35. if pt_session_options is None:
  36. pt_session_options = {}
  37. def get_prompt_tokens():
  38. return [(Token.Prompt, self.prompt)]
  39. if self._ptcomp is None:
  40. compl = IPCompleter(
  41. shell=self.shell, namespace={}, global_namespace={}, parent=self.shell
  42. )
  43. # add a completer for all the do_ methods
  44. methods_names = [m[3:] for m in dir(self) if m.startswith("do_")]
  45. def gen_comp(self, text):
  46. return [m for m in methods_names if m.startswith(text)]
  47. import types
  48. newcomp = types.MethodType(gen_comp, compl)
  49. compl.custom_matchers.insert(0, newcomp)
  50. # end add completer.
  51. self._ptcomp = IPythonPTCompleter(compl)
  52. # setup history only when we start pdb
  53. if self.shell.debugger_history is None:
  54. if self.shell.debugger_history_file is not None:
  55. p = Path(self.shell.debugger_history_file).expanduser()
  56. if not p.exists():
  57. p.touch()
  58. self.debugger_history = FileHistory(os.path.expanduser(str(p)))
  59. else:
  60. self.debugger_history = InMemoryHistory()
  61. else:
  62. self.debugger_history = self.shell.debugger_history
  63. options = dict(
  64. message=(lambda: PygmentsTokens(get_prompt_tokens())),
  65. editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
  66. key_bindings=create_ipython_shortcuts(self.shell),
  67. history=self.debugger_history,
  68. completer=self._ptcomp,
  69. enable_history_search=True,
  70. mouse_support=self.shell.mouse_support,
  71. complete_style=self.shell.pt_complete_style,
  72. style=getattr(self.shell, "style", None),
  73. color_depth=self.shell.color_depth,
  74. )
  75. if not PTK3:
  76. options['inputhook'] = self.shell.inputhook
  77. options.update(pt_session_options)
  78. if not _use_simple_prompt:
  79. self.pt_loop = asyncio.new_event_loop()
  80. self.pt_app = PromptSession(**options)
  81. def _prompt(self):
  82. """
  83. In case other prompt_toolkit apps have to run in parallel to this one (e.g. in madbg),
  84. create_app_session must be used to prevent mixing up between them. According to the prompt_toolkit docs:
  85. > If you need multiple applications running at the same time, you have to create a separate
  86. > `AppSession` using a `with create_app_session():` block.
  87. """
  88. with create_app_session():
  89. return self.pt_app.prompt()
  90. def cmdloop(self, intro=None):
  91. """Repeatedly issue a prompt, accept input, parse an initial prefix
  92. off the received input, and dispatch to action methods, passing them
  93. the remainder of the line as argument.
  94. override the same methods from cmd.Cmd to provide prompt toolkit replacement.
  95. """
  96. if not self.use_rawinput:
  97. raise ValueError('Sorry ipdb does not support use_rawinput=False')
  98. # In order to make sure that prompt, which uses asyncio doesn't
  99. # interfere with applications in which it's used, we always run the
  100. # prompt itself in a different thread (we can't start an event loop
  101. # within an event loop). This new thread won't have any event loop
  102. # running, and here we run our prompt-loop.
  103. self.preloop()
  104. try:
  105. if intro is not None:
  106. self.intro = intro
  107. if self.intro:
  108. print(self.intro, file=self.stdout)
  109. stop = None
  110. while not stop:
  111. if self.cmdqueue:
  112. line = self.cmdqueue.pop(0)
  113. else:
  114. self._ptcomp.ipy_completer.namespace = self.curframe_locals
  115. self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
  116. # Run the prompt in a different thread.
  117. if not _use_simple_prompt:
  118. try:
  119. line = self.thread_executor.submit(self._prompt).result()
  120. except EOFError:
  121. line = "EOF"
  122. else:
  123. line = input("ipdb> ")
  124. line = self.precmd(line)
  125. stop = self.onecmd(line)
  126. stop = self.postcmd(stop, line)
  127. self.postloop()
  128. except Exception:
  129. raise
  130. def do_interact(self, arg):
  131. ipshell = embed.InteractiveShellEmbed(
  132. config=self.shell.config,
  133. banner1="*interactive*",
  134. exit_msg="*exiting interactive console...*",
  135. )
  136. global_ns = self.curframe.f_globals
  137. ipshell(
  138. module=sys.modules.get(global_ns["__name__"], None),
  139. local_ns=self.curframe_locals,
  140. )
  141. def set_trace(frame=None):
  142. """
  143. Start debugging from `frame`.
  144. If frame is not specified, debugging starts from caller's frame.
  145. """
  146. TerminalPdb().set_trace(frame or sys._getframe().f_back)
  147. if __name__ == '__main__':
  148. import pdb
  149. # IPython.core.debugger.Pdb.trace_dispatch shall not catch
  150. # bdb.BdbQuit. When started through __main__ and an exception
  151. # happened after hitting "c", this is needed in order to
  152. # be able to quit the debugging session (see #9950).
  153. old_trace_dispatch = pdb.Pdb.trace_dispatch
  154. pdb.Pdb = TerminalPdb # type: ignore
  155. pdb.Pdb.trace_dispatch = old_trace_dispatch # type: ignore
  156. pdb.main()