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.ignore_environment and (startup_path := os.getenv("PYTHONSTARTUP")):
98 sys.audit("cpython.run_startup", startup_path)
99 try:
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 except SystemExit:
105 raise
106 except BaseException:
107 console.showtraceback()
108
109 ps1 = getattr(sys, "ps1", ">>> ")
110 if can_colorize() and CAN_USE_PYREPL:
111 ps1 = f"{ANSIColors.BOLD_MAGENTA}{ps1}{ANSIColors.RESET}"
112 console.write(f"{ps1}import asyncio\n")
113
114 if CAN_USE_PYREPL:
115 from _pyrepl.simple_interact import (
116 run_multiline_interactive_console,
117 )
118 try:
119 run_multiline_interactive_console(console)
120 except SystemExit:
121 # expected via the `exit` and `quit` commands
122 pass
123 except BaseException:
124 # unexpected issue
125 console.showtraceback()
126 console.write("Internal error, ")
127 return_code = 1
128 else:
129 console.interact(banner="", exitmsg="")
130 finally:
131 warnings.filterwarnings(
132 'ignore',
133 message=r'^coroutine .* was never awaited$',
134 category=RuntimeWarning)
135
136 loop.call_soon_threadsafe(loop.stop)
137
138 def interrupt(self) -> None:
139 if not CAN_USE_PYREPL:
140 return
141
142 from _pyrepl.simple_interact import _get_reader
143 r = _get_reader()
144 if r.threading_hook is not None:
145 r.threading_hook.add("") # type: ignore
146
147
148 if __name__ == '__main__':
149 sys.audit("cpython.run_stdin")
150
151 if not sys.flags.ignore_environment and os.getenv('PYTHON_BASIC_REPL'):
152 CAN_USE_PYREPL = False
153 else:
154 from _pyrepl.main import CAN_USE_PYREPL
155
156 return_code = 0
157 loop = asyncio.new_event_loop()
158 asyncio.set_event_loop(loop)
159
160 repl_locals = {'asyncio': asyncio}
161 for key in {'__name__', '__package__',
162 '__loader__', '__spec__',
163 '__builtins__', '__file__'}:
164 repl_locals[key] = locals()[key]
165
166 console = AsyncIOInteractiveConsole(repl_locals, loop)
167
168 repl_future = None
169 keyboard_interrupted = False
170
171 try:
172 import readline # NoQA
173 except ImportError:
174 readline = None
175
176 interactive_hook = getattr(sys, "__interactivehook__", None)
177
178 if interactive_hook is not None:
179 sys.audit("cpython.run_interactivehook", interactive_hook)
180 interactive_hook()
181
182 if interactive_hook is site.register_readline:
183 # Fix the completer function to use the interactive console locals
184 try:
185 import rlcompleter
186 except:
187 pass
188 else:
189 if readline is not None:
190 completer = rlcompleter.Completer(console.locals)
191 readline.set_completer(completer.complete)
192
193 repl_thread = REPLThread(name="Interactive thread")
194 repl_thread.daemon = True
195 repl_thread.start()
196
197 while True:
198 try:
199 loop.run_forever()
200 except KeyboardInterrupt:
201 keyboard_interrupted = True
202 if repl_future and not repl_future.done():
203 repl_future.cancel()
204 repl_thread.interrupt()
205 continue
206 else:
207 break
208
209 console.write('exiting asyncio REPL...\n')
210 loop.close()
211 sys.exit(return_code)