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 import warnings
34 import errno
35
36 from .readline import _get_reader, multiline_input, append_history_file
37
38
39 _error: tuple[type[Exception], ...] | type[Exception]
40 try:
41 from .unix_console import _error
42 except ModuleNotFoundError:
43 from .windows_console import _error
44
45 def check() -> str:
46 """Returns the error message if there is a problem initializing the state."""
47 try:
48 _get_reader()
49 except _error as e:
50 if term := os.environ.get("TERM", ""):
51 term = f"; TERM={term}"
52 return str(str(e) or repr(e) or "unknown error") + term
53 return ""
54
55
56 def _strip_final_indent(text: str) -> str:
57 # kill spaces and tabs at the end, but only if they follow '\n'.
58 # meant to remove the auto-indentation only (although it would of
59 # course also remove explicitly-added indentation).
60 short = text.rstrip(" \t")
61 n = len(short)
62 if n > 0 and text[n - 1] == "\n":
63 return short
64 return text
65
66
67 def _clear_screen():
68 reader = _get_reader()
69 reader.scheduled_commands.append("clear_screen")
70
71
72 REPL_COMMANDS = {
73 "exit": _sitebuiltins.Quitter('exit', ''),
74 "quit": _sitebuiltins.Quitter('quit' ,''),
75 "copyright": _sitebuiltins._Printer('copyright', sys.copyright),
76 "help": _sitebuiltins._Helper(),
77 "clear": _clear_screen,
78 "\x1a": _sitebuiltins.Quitter('\x1a', ''),
79 }
80
81
82 def _more_lines(console: code.InteractiveConsole, unicodetext: str) -> bool:
83 # ooh, look at the hack:
84 src = _strip_final_indent(unicodetext)
85 try:
86 code = console.compile(src, "<stdin>", "single")
87 except (OverflowError, SyntaxError, ValueError):
88 lines = src.splitlines(keepends=True)
89 if len(lines) == 1:
90 return False
91
92 last_line = lines[-1]
93 was_indented = last_line.startswith((" ", "\t"))
94 not_empty = last_line.strip() != ""
95 incomplete = not last_line.endswith("\n")
96 return (was_indented or not_empty) and incomplete
97 else:
98 return code is None
99
100
101 def run_multiline_interactive_console(
102 console: code.InteractiveConsole,
103 *,
104 future_flags: int = 0,
105 ) -> None:
106 from .readline import _setup
107 _setup(console.locals)
108 if future_flags:
109 console.compile.compiler.flags |= future_flags
110
111 more_lines = functools.partial(_more_lines, console)
112 input_n = 0
113
114 _is_x_showrefcount_set = sys._xoptions.get("showrefcount")
115 _is_pydebug_build = hasattr(sys, "gettotalrefcount")
116 show_ref_count = _is_x_showrefcount_set and _is_pydebug_build
117
118 def maybe_run_command(statement: str) -> bool:
119 statement = statement.strip()
120 if statement in console.locals or statement not in REPL_COMMANDS:
121 return False
122
123 reader = _get_reader()
124 reader.history.pop() # skip internal commands in history
125 command = REPL_COMMANDS[statement]
126 if callable(command):
127 # Make sure that history does not change because of commands
128 with reader.suspend_history(), reader.suspend_colorization():
129 command()
130 return True
131 return False
132
133 while True:
134 try:
135 try:
136 sys.stdout.flush()
137 except Exception:
138 pass
139
140 ps1 = getattr(sys, "ps1", ">>> ")
141 ps2 = getattr(sys, "ps2", "... ")
142 try:
143 statement = multiline_input(more_lines, ps1, ps2)
144 except EOFError:
145 break
146
147 if maybe_run_command(statement):
148 continue
149
150 input_name = f"<python-input-{input_n}>"
151 more = console.push(_strip_final_indent(statement), filename=input_name, _symbol="single") # type: ignore[call-arg]
152 assert not more
153 try:
154 append_history_file()
155 except (FileNotFoundError, PermissionError, OSError) as e:
156 warnings.warn(f"failed to open the history file for writing: {e}")
157
158 input_n += 1
159 except KeyboardInterrupt:
160 r = _get_reader()
161 r.cmpltn_reset()
162 if r.input_trans is r.isearch_trans:
163 r.do_cmd(("isearch-end", [""]))
164 r.pos = len(r.get_unicode())
165 r.dirty = True
166 r.refresh()
167 console.write("\nKeyboardInterrupt\n")
168 console.resetbuffer()
169 except MemoryError:
170 console.write("\nMemoryError\n")
171 console.resetbuffer()
172 except SystemExit:
173 raise
174 except:
175 console.showtraceback()
176 console.resetbuffer()
177 if show_ref_count:
178 console.write(
179 f"[{sys.gettotalrefcount()} refs,"
180 f" {sys.getallocatedblocks()} blocks]\n"
181 )