cli.py 6.7 KB

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