Debian Codegraph @

Lib/asyncio/__main__.py

raw
1 import argparse
2 import ast
3 import asyncio
4 import asyncio.tools
5 import concurrent.futures
6 import contextvars
7 import inspect
8 import os
9 import site
10 import sys
11 import threading
12 import types
13 import warnings
14
15 from _colorize import get_theme
16 from _pyrepl.console import InteractiveColoredConsole
17
18 from . import futures
19
20
21 class AsyncIOInteractiveConsole(InteractiveColoredConsole):
22
23 def __init__(self, locals, loop):
24 super().__init__(locals, filename="<stdin>")
25 self.compile.compiler.flags |= ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
26
27 self.loop = loop
28 self.context = contextvars.copy_context()
29
30 def runcode(self, code):
31 global return_code
32 future = concurrent.futures.Future()
33
34 def callback():
35 global return_code
36 global repl_future
37 global keyboard_interrupted
38
39 repl_future = None
40 keyboard_interrupted = False
41
42 func = types.FunctionType(code, self.locals)
43 try:
44 coro = func()
45 except SystemExit as se:
46 return_code = se.code
47 self.loop.stop()
48 return
49 except KeyboardInterrupt as ex:
50 keyboard_interrupted = True
51 future.set_exception(ex)
52 return
53 except BaseException as ex:
54 future.set_exception(ex)
55 return
56
57 if not inspect.iscoroutine(coro):
58 future.set_result(coro)
59 return
60
61 try:
62 repl_future = self.loop.create_task(coro, context=self.context)
63 futures._chain_future(repl_future, future)
64 except BaseException as exc:
65 future.set_exception(exc)
66
67 self.loop.call_soon_threadsafe(callback, context=self.context)
68
69 try:
70 return future.result()
71 except SystemExit as se:
72 return_code = se.code
73 self.loop.stop()
74 return
75 except BaseException:
76 if keyboard_interrupted:
77 if not CAN_USE_PYREPL:
78 self.write("\nKeyboardInterrupt\n")
79 else:
80 self.showtraceback()
81 return self.STATEMENT_FAILED
82
83 class REPLThread(threading.Thread):
84
85 def run(self):
86 global return_code
87
88 try:
89 if not sys.flags.quiet:
90 banner = (
91 f'asyncio REPL {sys.version} on {sys.platform}\n'
92 f'Use "await" directly instead of "asyncio.run()".\n'
93 f'Type "help", "copyright", "credits" or "license" '
94 f'for more information.\n'
95 )
96
97 console.write(banner)
98
99 if not sys.flags.ignore_environment and (startup_path := os.getenv("PYTHONSTARTUP")):
100 sys.audit("cpython.run_startup", startup_path)
101 try:
102 import tokenize
103 with tokenize.open(startup_path) as f:
104 startup_code = compile(f.read(), startup_path, "exec")
105 exec(startup_code, console.locals)
106 except SystemExit:
107 raise
108 except BaseException:
109 console.showtraceback()
110
111 ps1 = getattr(sys, "ps1", ">>> ")
112 if CAN_USE_PYREPL:
113 theme = get_theme().syntax
114 ps1 = f"{theme.prompt}{ps1}{theme.reset}"
115 console.write(f"{ps1}import asyncio\n")
116
117 if CAN_USE_PYREPL:
118 from _pyrepl.simple_interact import (
119 run_multiline_interactive_console,
120 )
121 try:
122 run_multiline_interactive_console(console)
123 except SystemExit:
124 # expected via the `exit` and `quit` commands
125 pass
126 except BaseException:
127 # unexpected issue
128 console.showtraceback()
129 console.write("Internal error, ")
130 return_code = 1
131 else:
132 console.interact(banner="", exitmsg="")
133 finally:
134 warnings.filterwarnings(
135 'ignore',
136 message=r'^coroutine .* was never awaited$',
137 category=RuntimeWarning)
138
139 loop.call_soon_threadsafe(loop.stop)
140
141 def interrupt(self) -> None:
142 if not CAN_USE_PYREPL:
143 return
144
145 from _pyrepl.simple_interact import _get_reader
146 r = _get_reader()
147 if r.threading_hook is not None:
148 r.threading_hook.add("") # type: ignore
149
150
151 if __name__ == '__main__':
152 parser = argparse.ArgumentParser(
153 prog="python3 -m asyncio",
154 description="Interactive asyncio shell and CLI tools",
155 color=True,
156 )
157 subparsers = parser.add_subparsers(help="sub-commands", dest="command")
158 ps = subparsers.add_parser(
159 "ps", help="Display a table of all pending tasks in a process"
160 )
161 ps.add_argument("pid", type=int, help="Process ID to inspect")
162 pstree = subparsers.add_parser(
163 "pstree", help="Display a tree of all pending tasks in a process"
164 )
165 pstree.add_argument("pid", type=int, help="Process ID to inspect")
166 args = parser.parse_args()
167 match args.command:
168 case "ps":
169 asyncio.tools.display_awaited_by_tasks_table(args.pid)
170 sys.exit(0)
171 case "pstree":
172 asyncio.tools.display_awaited_by_tasks_tree(args.pid)
173 sys.exit(0)
174 case None:
175 pass # continue to the interactive shell
176 case _:
177 # shouldn't happen as an invalid command-line wouldn't parse
178 # but let's keep it for the next person adding a command
179 print(f"error: unhandled command {args.command}", file=sys.stderr)
180 parser.print_usage(file=sys.stderr)
181 sys.exit(1)
182
183 sys.audit("cpython.run_stdin")
184
185 if not sys.flags.ignore_environment and os.getenv('PYTHON_BASIC_REPL'):
186 CAN_USE_PYREPL = False
187 else:
188 from _pyrepl.main import CAN_USE_PYREPL
189
190 return_code = 0
191 loop = asyncio.new_event_loop()
192 asyncio.set_event_loop(loop)
193
194 repl_locals = {
195 'asyncio': asyncio,
196 '__name__': __name__,
197 '__package__': None,
198 '__loader__': __loader__,
199 '__spec__': None,
200 '__builtins__': __builtins__,
201 }
202
203 console = AsyncIOInteractiveConsole(repl_locals, loop)
204
205 repl_future = None
206 keyboard_interrupted = False
207
208 try:
209 import readline # NoQA
210 except ImportError:
211 readline = None
212
213 interactive_hook = getattr(sys, "__interactivehook__", None)
214
215 if interactive_hook is not None:
216 sys.audit("cpython.run_interactivehook", interactive_hook)
217 interactive_hook()
218
219 if interactive_hook is site.register_readline:
220 # Fix the completer function to use the interactive console locals
221 try:
222 import rlcompleter
223 except:
224 pass
225 else:
226 if readline is not None:
227 completer = rlcompleter.Completer(console.locals)
228 readline.set_completer(completer.complete)
229
230 repl_thread = REPLThread(name="Interactive thread")
231 repl_thread.daemon = True
232 repl_thread.start()
233
234 while True:
235 try:
236 loop.run_forever()
237 except KeyboardInterrupt:
238 keyboard_interrupted = True
239 if repl_future and not repl_future.done():
240 repl_future.cancel()
241 repl_thread.interrupt()
242 continue
243 else:
244 break
245
246 console.write('exiting asyncio REPL...\n')
247 loop.close()
248 sys.exit(return_code)