Debian Codegraph @

src/trio/_repl.py

raw
1 from __future__ import annotations
2
3 import ast
4 import contextlib
5 import inspect
6 import sys
7 import warnings
8 from code import InteractiveConsole
9 from types import CodeType, FrameType, FunctionType
10 from typing import TYPE_CHECKING
11
12 import outcome
13
14 import trio
15 import trio.lowlevel
16 from trio._util import final
17
18 if TYPE_CHECKING:
19 from collections.abc import Callable
20
21
22 class SuppressDecorator(contextlib.ContextDecorator, contextlib.suppress):
23 pass
24
25
26 @SuppressDecorator(KeyboardInterrupt)
27 @trio.lowlevel.disable_ki_protection
28 def terminal_newline() -> None: # TODO: test this line
29 import fcntl
30 import termios
31
32 # Fake up a newline char as if user had typed it at the terminal
33 try:
34 fcntl.ioctl(sys.stdin, termios.TIOCSTI, b"\n") # type: ignore[attr-defined, unused-ignore]
35 except OSError as e:
36 print(f"\nPress enter! Newline injection failed: {e}", end="", flush=True)
37
38
39 @final
40 class TrioInteractiveConsole(InteractiveConsole):
41 def __init__(self, repl_locals: dict[str, object] | None = None) -> None:
42 super().__init__(locals=repl_locals)
43 self.token: trio.lowlevel.TrioToken | None = None
44 self.compile.compiler.flags |= ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
45 self.interrupted = False
46
47 def runcode(self, code: CodeType) -> None:
48 func = FunctionType(code, self.locals)
49 if inspect.iscoroutinefunction(func):
50 result = trio.from_thread.run(outcome.acapture, func)
51 else:
52 result = trio.from_thread.run_sync(outcome.capture, func)
53 if isinstance(result, outcome.Error):
54 # If it is SystemExit, quit the repl. Otherwise, print the traceback.
55 # If there is a SystemExit inside a BaseExceptionGroup, it probably isn't
56 # the user trying to quit the repl, but rather an error in the code. So, we
57 # don't try to inspect groups for SystemExit. Instead, we just print and
58 # return to the REPL.
59 if isinstance(result.error, SystemExit):
60 raise result.error
61 else:
62 # Inline our own version of self.showtraceback that can use
63 # outcome.Error.error directly to print clean tracebacks.
64 # This also means overriding self.showtraceback does nothing.
65 sys.last_type, sys.last_value = type(result.error), result.error
66 sys.last_traceback = result.error.__traceback__
67 # see https://docs.python.org/3/library/sys.html#sys.last_exc
68 if sys.version_info >= (3, 12):
69 sys.last_exc = result.error
70
71 # We always use sys.excepthook, unlike other implementations.
72 # This means that overriding self.write also does nothing to tbs.
73 sys.excepthook(sys.last_type, sys.last_value, sys.last_traceback)
74 # clear any residual KI
75 trio.from_thread.run(trio.lowlevel.checkpoint_if_cancelled)
76 # trio.from_thread.check_cancelled() has too long of a memory
77
78 if sys.platform == "win32": # TODO: test this line
79
80 def raw_input(self, prompt: str = "") -> str:
81 try:
82 return input(prompt)
83 except EOFError:
84 # check if trio has a pending KI
85 trio.from_thread.run(trio.lowlevel.checkpoint_if_cancelled)
86 raise
87
88 else:
89
90 def raw_input(self, prompt: str = "") -> str:
91 from signal import SIGINT, signal
92
93 assert not self.interrupted
94
95 def install_handler() -> (
96 Callable[[int, FrameType | None], None] | int | None
97 ):
98 def handler(
99 sig: int, frame: FrameType | None
100 ) -> None: # TODO: test this line
101 self.interrupted = True
102 token.run_sync_soon(terminal_newline, idempotent=True)
103
104 token = trio.lowlevel.current_trio_token()
105
106 return signal(SIGINT, handler)
107
108 prev_handler = trio.from_thread.run_sync(install_handler)
109 try:
110 return input(prompt)
111 finally:
112 trio.from_thread.run_sync(signal, SIGINT, prev_handler)
113 if self.interrupted: # TODO: test this line
114 raise KeyboardInterrupt
115
116 def write(self, output: str) -> None:
117 if self.interrupted: # TODO: test this line
118 assert output == "\nKeyboardInterrupt\n"
119 sys.stderr.write(output[1:])
120 self.interrupted = False
121 else:
122 sys.stderr.write(output)
123
124
125 async def run_repl(console: TrioInteractiveConsole) -> None:
126 banner = (
127 f"trio REPL {sys.version} on {sys.platform}\n"
128 f'Use "await" directly instead of "trio.run()".\n'
129 f'Type "help", "copyright", "credits" or "license" '
130 f"for more information.\n"
131 f'{getattr(sys, "ps1", ">>> ")}import trio'
132 )
133 try:
134 await trio.to_thread.run_sync(console.interact, banner)
135 finally:
136 warnings.filterwarnings(
137 "ignore",
138 message=r"^coroutine .* was never awaited$",
139 category=RuntimeWarning,
140 )
141
142
143 def main(original_locals: dict[str, object]) -> None:
144 with contextlib.suppress(ImportError):
145 import readline # noqa: F401
146
147 repl_locals: dict[str, object] = {"trio": trio}
148 for key in {
149 "__name__",
150 "__package__",
151 "__loader__",
152 "__spec__",
153 "__builtins__",
154 "__file__",
155 }:
156 repl_locals[key] = original_locals[key]
157
158 console = TrioInteractiveConsole(repl_locals)
159 trio.run(run_repl, console)