Debian Codegraph @

Lib/asyncio/__main__.py

raw
1 import ast
2 import asyncio
3 import concurrent.futures
4 import contextvars
5 import inspect
6 import os
7 import site
8 import sys
9 import threading
10 import types
11 import warnings
12
13 from _colorize import can_colorize, ANSIColors # type: ignore[import-not-found]
14 from _pyrepl.console import InteractiveColoredConsole
15
16 from . import futures
17
18
19 class AsyncIOInteractiveConsole(InteractiveColoredConsole):
20
21 def __init__(self, locals, loop):
22 super().__init__(locals, filename="<stdin>")
23 self.compile.compiler.flags |= ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
24
25 self.loop = loop
26 self.context = contextvars.copy_context()
27
28 def runcode(self, code):
29 global return_code
30 future = concurrent.futures.Future()
31
32 def callback():
33 global return_code
34 global repl_future
35 global keyboard_interrupted
36
37 repl_future = None
38 keyboard_interrupted = False
39
40 func = types.FunctionType(code, self.locals)
41 try:
42 coro = func()
43 except SystemExit as se:
44 return_code = se.code
45 self.loop.stop()
46 return
47 except KeyboardInterrupt as ex:
48 keyboard_interrupted = True
49 future.set_exception(ex)
50 return
51 except BaseException as ex:
52 future.set_exception(ex)
53 return
54
55 if not inspect.iscoroutine(coro):
56 future.set_result(coro)
57 return
58
59 try:
60 repl_future = self.loop.create_task(coro, context=self.context)
61 futures._chain_future(repl_future, future)
62 except BaseException as exc:
63 future.set_exception(exc)
64
65 self.loop.call_soon_threadsafe(callback, context=self.context)
66
67 try:
68 return future.result()
69 except SystemExit as se:
70 return_code = se.code
71 self.loop.stop()
72 return
73 except BaseException:
74 if keyboard_interrupted:
75 if not CAN_USE_PYREPL:
76 self.write("\nKeyboardInterrupt\n")
77 else:
78 self.showtraceback()
79 return self.STATEMENT_FAILED
80
81 class REPLThread(threading.Thread):
82
83 def run(self):
84 global return_code
85
86 try:
87 if not sys.flags.quiet:
88 banner = (
89 f'asyncio REPL {sys.version} on {sys.platform}\n'
90 f'Use "await" directly instead of "asyncio.run()".\n'
91 f'Type "help", "copyright", "credits" or "license" '
92 f'for more information.\n'
93 )
94
95 console.write(banner)
96
97 if not sys.flags.isolated and (startup_path := os.getenv("PYTHONSTARTUP")):
98 sys.audit("cpython.run_startup", startup_path)
99
100 import tokenize
101 with tokenize.open(startup_path) as f:
102 startup_code = compile(f.read(), startup_path, "exec")
103 exec(startup_code, console.locals)
104
105 ps1 = getattr(sys, "ps1", ">>> ")
106 if can_colorize() and CAN_USE_PYREPL:
107 ps1 = f"{ANSIColors.BOLD_MAGENTA}{ps1}{ANSIColors.RESET}"
108 console.write(f"{ps1}import asyncio\n")
109
110 if CAN_USE_PYREPL:
111 from _pyrepl.simple_interact import (
112 run_multiline_interactive_console,
113 )
114 try:
115 run_multiline_interactive_console(console)
116 except SystemExit:
117 # expected via the `exit` and `quit` commands
118 pass
119 except BaseException:
120 # unexpected issue
121 console.showtraceback()
122 console.write("Internal error, ")
123 return_code = 1
124 else:
125 console.interact(banner="", exitmsg="")
126 finally:
127 warnings.filterwarnings(
128 'ignore',
129 message=r'^coroutine .* was never awaited$',
130 category=RuntimeWarning)
131
132 loop.call_soon_threadsafe(loop.stop)
133
134 def interrupt(self) -> None:
135 if not CAN_USE_PYREPL:
136 return
137
138 from _pyrepl.simple_interact import _get_reader
139 r = _get_reader()
140 if r.threading_hook is not None:
141 r.threading_hook.add("") # type: ignore
142
143
144 if __name__ == '__main__':
145 sys.audit("cpython.run_stdin")
146
147 if os.getenv('PYTHON_BASIC_REPL'):
148 CAN_USE_PYREPL = False
149 else:
150 from _pyrepl.main import CAN_USE_PYREPL
151
152 return_code = 0
153 loop = asyncio.new_event_loop()
154 asyncio.set_event_loop(loop)
155
156 repl_locals = {'asyncio': asyncio}
157 for key in {'__name__', '__package__',
158 '__loader__', '__spec__',
159 '__builtins__', '__file__'}:
160 repl_locals[key] = locals()[key]
161
162 console = AsyncIOInteractiveConsole(repl_locals, loop)
163
164 repl_future = None
165 keyboard_interrupted = False
166
167 try:
168 import readline # NoQA
169 except ImportError:
170 readline = None
171
172 interactive_hook = getattr(sys, "__interactivehook__", None)
173
174 if interactive_hook is not None:
175 sys.audit("cpython.run_interactivehook", interactive_hook)
176 interactive_hook()
177
178 if interactive_hook is site.register_readline:
179 # Fix the completer function to use the interactive console locals
180 try:
181 import rlcompleter
182 except:
183 pass
184 else:
185 if readline is not None:
186 completer = rlcompleter.Completer(console.locals)
187 readline.set_completer(completer.complete)
188
189 repl_thread = REPLThread(name="Interactive thread")
190 repl_thread.daemon = True
191 repl_thread.start()
192
193 while True:
194 try:
195 loop.run_forever()
196 except KeyboardInterrupt:
197 keyboard_interrupted = True
198 if repl_future and not repl_future.done():
199 repl_future.cancel()
200 repl_thread.interrupt()
201 continue
202 else:
203 break
204
205 console.write('exiting asyncio REPL...\n')
206 loop.close()
207 sys.exit(return_code)