Debian Codegraph @

friendly_traceback/ft_console.py

raw symbols SCIP
1 """
2 ft_console.py
3 ==========
4
5 Adaptation of Python's console found in code.py so that it can be
6 used to show some friendly tracebacks.
7 """
8
9 import codeop # need to import to exclude from tracebacks
10 import os
11 import platform
12 import sys
13 import traceback
14 import types
15 from code import InteractiveConsole
16 from typing import Any, Callable, Mapping, Optional, Union
17
18 import friendly_traceback
19
20 from . import source_cache
21 from .config import did_exception_occur_before, session
22 from .console_helpers import friendly_tb, helpers
23 from .ft_gettext import current_lang
24 from .typing_info import Formatter, InclusionChoice
25
26
27 def type_friendly() -> str:
28 # Explicit type as mypy cannot infer correctly the return type on its own here
29 _: Callable[[str], str] = current_lang.translate
30 if sys.platform == "win32":
31 exit_ = _("Use exit() or Ctrl-Z plus Return to exit.") + "\n"
32 else:
33 exit_ = _("Use exit() or Ctrl-D to exit.") + "\n"
34 return exit_ + _("Type 'Friendly' for help on special functions/methods.")
35
36
37 BANNER = f"""Friendly-traceback version {friendly_traceback.__version__}
38 Python version: {platform.python_version()}
39 """
40
41
42 _old_displayhook = sys.displayhook
43
44
45 def rich_displayhook(value: Any) -> None:
46 """Custom display hook intended to show some brief function descriptions
47 that can be translated into various languages, for functions that have
48 a custom '__rich_repr__' attribute.
49 Compatible with Rich (https://github.com/willmcgugan/rich)
50 """
51 if value is None:
52 return
53 if str(type(value)) == "<class 'function'>" and hasattr(value, "__rich_repr__"):
54 print(f"{value.__name__}(): {value.__rich_repr__()[0]}")
55 return
56 _old_displayhook(value)
57
58
59 def toggle_prompt() -> None:
60 """Toggles the style of prompt to use in the console."""
61 session.ipython_prompt = not session.ipython_prompt
62
63
64 class FriendlyTracebackConsole(InteractiveConsole):
65 def __init__(
66 self,
67 local_vars: Optional[Mapping[str, Any]] = None,
68 formatter: Union[str, Formatter] = "repl",
69 displayhook: Optional[Callable[[object], Any]] = None,
70 ipython_prompt: bool = True,
71 ) -> None:
72 """This class builds upon Python's code.InteractiveConsole
73 to provide friendly tracebacks. It keeps track
74 of code fragment executed by treating each of them as
75 an individual source file.
76 """
77 _ = current_lang.translate
78 friendly_traceback.exclude_file_from_traceback(codeop.__file__)
79 self.fake_filename = "<friendly-console:%d>"
80 self.counter = 1
81 friendly_traceback.set_formatter(formatter)
82 if displayhook is not None:
83 sys.displayhook = displayhook
84 session.ipython_prompt = ipython_prompt
85 if session.ipython_prompt:
86 sys.ps1 = "[1]: "
87 sys.ps2 = "...: "
88 super().__init__(locals=local_vars)
89 session.suggest_console = ""
90
91 def interact(self, banner=None, exitmsg=None) -> None:
92 if not session.exception_before_import and did_exception_occur_before():
93 print(banner)
94 banner = ""
95 friendly_tb()
96 super().interact(banner=banner, exitmsg=exitmsg)
97
98 def push(self, line: str) -> bool:
99 """Push a line to the interpreter.
100
101 The line should not have a trailing newline; it may have
102 internal newlines. The line is appended to a buffer and the
103 interpreter's runsource() method is called with the
104 concatenated contents of the buffer as source. If this
105 indicates that the command was executed or invalid, the buffer
106 is reset; otherwise, the command is incomplete, and the buffer
107 is left as it was after the line was appended. The return
108 value is True if more input is required, False if the line was dealt
109 with in some way (this is the same as runsource()).
110 """
111 # mypy cannot get the type information from InteractiveConsole in stdlib
112 self.buffer.append(line)
113 source = "\n".join(self.buffer)
114
115 # Each valid code sample is saved with its own fake filename.
116 # They are numbered consecutively to help understand
117 # the traceback history.
118 # If self.counter was not updated, it means that the previous
119 # code sample was not valid, and we reuse the same file name
120 filename = self.fake_filename % self.counter
121 source_cache.cache.add(filename, source)
122
123 more = self.runsource(source, filename)
124 if not more:
125 self.resetbuffer()
126 self.counter += 1
127 if session.ipython_prompt:
128 sys.ps1 = f"\n[{self.counter}]: "
129 sys.ps2 = " " * (len(str(self.counter)) - 1) + "...: "
130 else:
131 sys.ps1 = ">>> "
132 sys.ps2 = "... "
133 return more
134
135 def runsource(
136 self, source: str, filename: str = "<friendly-console>", symbol: str = "single"
137 ) -> bool:
138 """Compile and run some source in the interpreter.
139
140 Arguments are as for compile_command().
141
142 One several things can happen:
143
144 1) The input is incorrect; compile_command() raised an
145 exception (SyntaxError or OverflowError). A syntax traceback
146 will be printed .
147
148 2) The input is incomplete, and more input is required;
149 compile_command() returned None. Nothing happens.
150
151 3) The input is complete; compile_command() returned a code
152 object. The code is executed by calling self.runcode() (which
153 also handles run-time exceptions, except for SystemExit).
154
155 The return value is True in case 2, False in the other cases (unless
156 an exception is raised). The return value can be used to
157 decide whether to use sys.ps1 or sys.ps2 to prompt the next
158 line.
159 """
160 try:
161 code = self.compile(source, filename, symbol)
162 except (OverflowError, SyntaxError, ValueError):
163 # Case 1
164 if session.installed:
165 friendly_traceback.explain_traceback()
166 else:
167 super().showsyntaxerror(filename)
168 return False
169
170 if code is None:
171 # Case 2
172 return True
173
174 # Case 3
175 self.runcode(code)
176 return False
177
178 def runcode(self, code: types.CodeType) -> None:
179 """Execute a code object.
180
181 When an exception occurs, friendly_traceback.explain_traceback() is called to
182 display a traceback. All exceptions are caught except
183 SystemExit, which, unlike the case for the original version in the
184 standard library, cleanly exists the program. This is done
185 to avoid our Friendly's exception hook to intercept it and confuse the users.
186
187 A note about KeyboardInterrupt: this exception may occur
188 elsewhere in this code, and may not always be caught. The
189 caller should be prepared to deal with it.
190 """
191 _ = current_lang.translate
192 try:
193 exec(code, self.locals) # type: ignore
194 except SystemExit:
195 os._exit(1) # noqa -pycharm
196 except Exception: # noqa
197 if session.installed:
198 try:
199 friendly_traceback.explain_traceback()
200 except Exception: # noqa
201 print("Friendly Internal Error")
202 print("-" * 60)
203 traceback.print_exc()
204 print("-" * 60)
205 else:
206 super().showtraceback()
207
208 # The following two methods are never used in this class, but they are
209 # defined in the parent class. The following are the equivalent methods
210 # that can be used if an explicit call is desired for some reason.
211
212 def showsyntaxerror(self, filename: Optional[str] = None) -> None:
213 if session.installed:
214 friendly_traceback.explain_traceback()
215 else:
216 super().showsyntaxerror(filename)
217
218 def showtraceback(self) -> None:
219 if session.installed:
220 friendly_traceback.explain_traceback()
221 else:
222 super().showtraceback()
223
224
225 def start_console(
226 local_vars: Optional[Mapping[str, Any]] = None,
227 formatter: Union[str, Formatter] = "repl",
228 include: InclusionChoice = "friendly_tb",
229 lang: str = "en",
230 banner: Optional[str] = None,
231 displayhook: Optional[Callable[[object], Any]] = None,
232 ipython_prompt: bool = True,
233 ) -> None:
234 """Starts a console; modified from code.interact"""
235
236 friendly_traceback.about_warnings.enable_warnings()
237 if banner is None:
238 banner = BANNER + type_friendly() + "\n"
239 if displayhook is None:
240 displayhook = rich_displayhook
241
242 friendly_traceback.install(include=include, lang=lang)
243
244 if local_vars is not None:
245 # Make sure we don't overwrite with our own functions
246 helpers.update(local_vars)
247 helpers["friendly_exec"] = friendly_traceback.friendly_exec
248 helpers["toggle_prompt"] = toggle_prompt
249
250 console = FriendlyTracebackConsole(
251 local_vars=helpers,
252 formatter=formatter,
253 displayhook=displayhook,
254 ipython_prompt=ipython_prompt,
255 )
256 console.interact(banner=banner)