Debian Codegraph @

src/websockets/cli.py

raw
1 from __future__ import annotations
2
3 import argparse
4 import asyncio
5 import itertools
6 import os
7 import ssl
8 import sys
9 import threading
10 from typing import Any, Callable
11
12 from .asyncio.client import ClientConnection, connect
13 from .exceptions import ConnectionClosed
14 from .frames import Close
15 from .version import version as websockets_version
16
17
18 __all__ = ["main"]
19
20 # Escape ASCII control characters (0-31 and 128-159) as well as DEL (127).
21 # Do not escape NO-BREAK SPACE (160) and SOFT HYPHEN (173), even if Python
22 # considers them non-printable, since they don't cause issues in terminal.
23
24 # >>> [i for i in range(256) if not any((
25 # ... chr(i).isprintable(),
26 # ... i < 32,
27 # ... i == 127,
28 # ... 128 <= i < 160,
29 # ... ))]
30 # [160, 173]
31
32 TERMINAL_ESCAPES = str.maketrans(
33 {i: repr(chr(i))[1:-1] for i in itertools.chain(range(32), range(127, 160))}
34 )
35
36
37 def escape(string: str) -> str:
38 """Make a string safe for a terminal by escaping control characters."""
39 return string.translate(TERMINAL_ESCAPES)
40
41
42 def print_during_input(string: str) -> None:
43 sys.stdout.write(
44 # Save cursor position
45 "\N{ESC}7"
46 # Add a new line
47 "\N{LINE FEED}"
48 # Move cursor up
49 "\N{ESC}[A"
50 # Insert blank line, scroll last line down
51 "\N{ESC}[L"
52 # Print string in the inserted blank line
53 f"{string}\N{LINE FEED}"
54 # Restore cursor position
55 "\N{ESC}8"
56 # Move cursor down
57 "\N{ESC}[B"
58 )
59 sys.stdout.flush()
60
61
62 def print_over_input(string: str) -> None:
63 sys.stdout.write(
64 # Move cursor to beginning of line
65 "\N{CARRIAGE RETURN}"
66 # Delete current line
67 "\N{ESC}[K"
68 # Print string
69 f"{string}\N{LINE FEED}"
70 )
71 sys.stdout.flush()
72
73
74 async def print_incoming_messages(websocket: ClientConnection) -> None:
75 async for message in websocket:
76 if isinstance(message, str):
77 print_during_input("< " + escape(message))
78 else:
79 print_during_input("< (binary) " + message.hex())
80
81
82 def read_outgoing_messages(
83 queue_for_sending: Callable[[str], None],
84 notify_end_of_file: Callable[[], None],
85 ) -> None:
86 while True:
87 sys.stdout.write("> ")
88 sys.stdout.flush()
89 line = sys.stdin.readline()
90 if not line:
91 notify_end_of_file()
92 break
93 message = line.rstrip("\r\n")
94 queue_for_sending(message)
95
96
97 async def send_outgoing_messages(
98 websocket: ClientConnection,
99 messages: asyncio.Queue[str],
100 ) -> None:
101 while True:
102 message = await messages.get()
103 try:
104 await websocket.send(message)
105 except ConnectionClosed: # pragma: no cover
106 break
107
108
109 async def interactive_client(uri: str, **kwargs: Any) -> None:
110 try:
111 websocket = await connect(uri, **kwargs)
112 except Exception as exc:
113 print(f"Failed to connect to {uri}: {exc}.")
114 sys.exit(1)
115 else:
116 print(f"Connected to {uri}.")
117
118 # Read messages from stdin in a thread because Windows doesn't support
119 # reading asynchronously (#1681), and a daemon thread to avoid blocking
120 # Ctrl-C because signals are only delivered to the main thread.
121 loop = asyncio.get_event_loop()
122 messages: asyncio.Queue[str] = asyncio.Queue()
123 # When dropping support for Python < 3.13, change notify_end_of_file() to
124 # call messages.shutdown() and break when asyncio.QueueShutdownError is
125 # raised in send_outgoing_messages().
126 shutdown: asyncio.Future[None] = loop.create_future()
127
128 def queue_for_sending(message: str) -> None:
129 try:
130 loop.call_soon_threadsafe(messages.put_nowait, message)
131 except RuntimeError: # Event loop is closed # pragma: no cover
132 pass
133
134 def notify_end_of_file() -> None:
135 try:
136 loop.call_soon_threadsafe(shutdown.set_result, None)
137 except RuntimeError: # Event loop is closed # pragma: no cover
138 pass
139
140 threading.Thread(
141 target=read_outgoing_messages,
142 args=(queue_for_sending, notify_end_of_file),
143 daemon=True,
144 ).start()
145
146 incoming = asyncio.create_task(print_incoming_messages(websocket))
147 outgoing = asyncio.create_task(send_outgoing_messages(websocket, messages))
148 try:
149 await asyncio.wait(
150 [incoming, outgoing, shutdown],
151 # Clean up and exit when the server closes the connection
152 # or the user enters EOT (^D), whichever happens first.
153 return_when=asyncio.FIRST_COMPLETED,
154 )
155 # asyncio.run() cancels the main task when the user triggers SIGINT (^C).
156 # https://docs.python.org/3/library/asyncio-runner.html#handling-keyboard-interruption
157 # Clean up and exit without re-raising CancelledError to prevent Python
158 # from raising KeyboardInterrupt and displaying a stack track.
159 except asyncio.CancelledError: # pragma: no cover
160 pass
161 finally:
162 incoming.cancel()
163 outgoing.cancel()
164
165 await websocket.close()
166 assert websocket.close_code is not None and websocket.close_reason is not None
167 close_status = Close(websocket.close_code, websocket.close_reason)
168 print_over_input(f"Connection closed: {escape(str(close_status))}.")
169
170
171 def main(argv: list[str] | None = None) -> None:
172 parser = argparse.ArgumentParser(
173 prog="websockets",
174 description="Interactive WebSocket client.",
175 add_help=False,
176 )
177 parser.add_argument(
178 "--help",
179 action="store_true",
180 help="show usage and exit",
181 )
182 parser.add_argument(
183 "--insecure",
184 action="store_true",
185 help="disable TLS certificate verification",
186 )
187 parser.add_argument(
188 "--version",
189 action="store_true",
190 help="show version and exit",
191 )
192 parser.add_argument(
193 "uri",
194 metavar="<uri>",
195 nargs="?",
196 )
197 args = parser.parse_args(argv)
198
199 if args.help:
200 parser.print_usage()
201 sys.exit(0)
202
203 if args.version:
204 print(f"websockets {websockets_version}")
205 sys.exit(0)
206
207 if args.uri is None:
208 parser.print_usage()
209 sys.exit(2)
210
211 # Enable VT100 to support ANSI escape codes in Command Prompt on Windows.
212 # See https://github.com/python/cpython/issues/74261 for why this works.
213 if sys.platform == "win32":
214 os.system("")
215
216 try:
217 import readline # noqa: F401
218 except ImportError: # readline isn't available on all platforms
219 pass
220
221 kwargs = {}
222 if args.insecure and args.uri.startswith("wss://"):
223 # This isn't a public API but it's mentioned in the changelog:
224 # https://docs.python.org/3/whatsnew/3.4.html#changed-in-3-4-3
225 kwargs["ssl"] = ssl._create_unverified_context()
226
227 asyncio.run(interactive_client(args.uri, **kwargs))