Debian Codegraph @

Lib/_pyrepl/simple_interact.py

raw
1 # Copyright 2000-2010 Michael Hudson-Doyle <[email protected]>
2 # Armin Rigo
3 #
4 # All Rights Reserved
5 #
6 #
7 # Permission to use, copy, modify, and distribute this software and
8 # its documentation for any purpose is hereby granted without fee,
9 # provided that the above copyright notice appear in all copies and
10 # that both that copyright notice and this permission notice appear in
11 # supporting documentation.
12 #
13 # THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
14 # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15 # AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
16 # INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
17 # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
18 # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
19 # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20
21 """This is an alternative to python_reader which tries to emulate
22 the CPython prompt as closely as possible, with the exception of
23 allowing multiline input and multiline history entries.
24 """
25
26 from __future__ import annotations
27
28 import _sitebuiltins
29 import functools
30 import os
31 import sys
32 import code
33
34 from .readline import _get_reader, multiline_input
35
36 TYPE_CHECKING = False
37
38 if TYPE_CHECKING:
39 from typing import Any
40
41
42 _error: tuple[type[Exception], ...] | type[Exception]
43 try:
44 from .unix_console import _error
45 except ModuleNotFoundError:
46 from .windows_console import _error
47
48 def check() -> str:
49 """Returns the error message if there is a problem initializing the state."""
50 try:
51 _get_reader()
52 except _error as e:
53 if term := os.environ.get("TERM", ""):
54 term = f"; TERM={term}"
55 return str(str(e) or repr(e) or "unknown error") + term
56 return ""
57
58
59 def _strip_final_indent(text: str) -> str:
60 # kill spaces and tabs at the end, but only if they follow '\n'.
61 # meant to remove the auto-indentation only (although it would of
62 # course also remove explicitly-added indentation).
63 short = text.rstrip(" \t")
64 n = len(short)
65 if n > 0 and text[n - 1] == "\n":
66 return short
67 return text
68
69
70 def _clear_screen():
71 reader = _get_reader()
72 reader.scheduled_commands.append("clear_screen")
73
74
75 REPL_COMMANDS = {
76 "exit": _sitebuiltins.Quitter('exit', ''),
77 "quit": _sitebuiltins.Quitter('quit' ,''),
78 "copyright": _sitebuiltins._Printer('copyright', sys.copyright),
79 "help": _sitebuiltins._Helper(),
80 "clear": _clear_screen,
81 "\x1a": _sitebuiltins.Quitter('\x1a', ''),
82 }
83
84
85 def _more_lines(console: code.InteractiveConsole, unicodetext: str) -> bool:
86 # ooh, look at the hack:
87 src = _strip_final_indent(unicodetext)
88 try:
89 code = console.compile(src, "<stdin>", "single")
90 except (OverflowError, SyntaxError, ValueError):
91 lines = src.splitlines(keepends=True)
92 if len(lines) == 1:
93 return False
94
95 last_line = lines[-1]
96 was_indented = last_line.startswith((" ", "\t"))
97 not_empty = last_line.strip() != ""
98 incomplete = not last_line.endswith("\n")
99 return (was_indented or not_empty) and incomplete
100 else:
101 return code is None
102
103
104 def run_multiline_interactive_console(
105 console: code.InteractiveConsole,
106 *,
107 future_flags: int = 0,
108 ) -> None:
109 from .readline import _setup
110 _setup(console.locals)
111 if future_flags:
112 console.compile.compiler.flags |= future_flags
113
114 more_lines = functools.partial(_more_lines, console)
115 input_n = 0
116
117 _is_x_showrefcount_set = sys._xoptions.get("showrefcount")
118 _is_pydebug_build = hasattr(sys, "gettotalrefcount")
119 show_ref_count = _is_x_showrefcount_set and _is_pydebug_build
120
121 def maybe_run_command(statement: str) -> bool:
122 statement = statement.strip()
123 if statement in console.locals or statement not in REPL_COMMANDS:
124 return False
125
126 reader = _get_reader()
127 reader.history.pop() # skip internal commands in history
128 command = REPL_COMMANDS[statement]
129 if callable(command):
130 # Make sure that history does not change because of commands
131 with reader.suspend_history():
132 command()
133 return True
134 return False
135
136 while 1:
137 try:
138 try:
139 sys.stdout.flush()
140 except Exception:
141 pass
142
143 ps1 = getattr(sys, "ps1", ">>> ")
144 ps2 = getattr(sys, "ps2", "... ")
145 try:
146 statement = multiline_input(more_lines, ps1, ps2)
147 except EOFError:
148 break
149
150 if maybe_run_command(statement):
151 continue
152
153 input_name = f"<python-input-{input_n}>"
154 more = console.push(_strip_final_indent(statement), filename=input_name, _symbol="single") # type: ignore[call-arg]
155 assert not more
156 input_n += 1
157 except KeyboardInterrupt:
158 r = _get_reader()
159 r.cmpltn_reset()
160 if r.input_trans is r.isearch_trans:
161 r.do_cmd(("isearch-end", [""]))
162 r.pos = len(r.get_unicode())
163 r.dirty = True
164 r.refresh()
165 r.in_bracketed_paste = False
166 console.write("\nKeyboardInterrupt\n")
167 console.resetbuffer()
168 except MemoryError:
169 console.write("\nMemoryError\n")
170 console.resetbuffer()
171 except SystemExit:
172 raise
173 except:
174 console.showtraceback()
175 console.resetbuffer()
176 if show_ref_count:
177 console.write(
178 f"[{sys.gettotalrefcount()} refs,"
179 f" {sys.getallocatedblocks()} blocks]\n"
180 )