cli.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. from __future__ import annotations
  2. import argparse
  3. import asyncio
  4. import itertools
  5. import os
  6. import sys
  7. from typing import Generator
  8. from .asyncio.client import ClientConnection, connect
  9. from .asyncio.messages import SimpleQueue
  10. from .exceptions import ConnectionClosed
  11. from .frames import Close
  12. from .streams import StreamReader
  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. class ReadLines(asyncio.Protocol):
  60. def __init__(self) -> None:
  61. self.reader = StreamReader()
  62. self.messages: SimpleQueue[str] = SimpleQueue()
  63. def parse(self) -> Generator[None, None, None]:
  64. while True:
  65. sys.stdout.write("> ")
  66. sys.stdout.flush()
  67. line = yield from self.reader.read_line(sys.maxsize)
  68. self.messages.put(line.decode().rstrip("\r\n"))
  69. def connection_made(self, transport: asyncio.BaseTransport) -> None:
  70. self.parser = self.parse()
  71. next(self.parser)
  72. def data_received(self, data: bytes) -> None:
  73. self.reader.feed_data(data)
  74. next(self.parser)
  75. def eof_received(self) -> None:
  76. self.reader.feed_eof()
  77. # next(self.parser) isn't useful and would raise EOFError.
  78. def connection_lost(self, exc: Exception | None) -> None:
  79. self.reader.discard()
  80. self.messages.abort()
  81. async def print_incoming_messages(websocket: ClientConnection) -> None:
  82. async for message in websocket:
  83. if isinstance(message, str):
  84. print_during_input("< " + escape(message))
  85. else:
  86. print_during_input("< (binary) " + message.hex())
  87. async def send_outgoing_messages(
  88. websocket: ClientConnection,
  89. messages: SimpleQueue[str],
  90. ) -> None:
  91. while True:
  92. try:
  93. message = await messages.get()
  94. except EOFError:
  95. break
  96. try:
  97. await websocket.send(message)
  98. except ConnectionClosed: # pragma: no cover
  99. break
  100. async def interactive_client(uri: str) -> None:
  101. try:
  102. websocket = await connect(uri)
  103. except Exception as exc:
  104. print(f"Failed to connect to {uri}: {exc}.")
  105. sys.exit(1)
  106. else:
  107. print(f"Connected to {uri}.")
  108. loop = asyncio.get_running_loop()
  109. transport, protocol = await loop.connect_read_pipe(ReadLines, sys.stdin)
  110. incoming = asyncio.create_task(
  111. print_incoming_messages(websocket),
  112. )
  113. outgoing = asyncio.create_task(
  114. send_outgoing_messages(websocket, protocol.messages),
  115. )
  116. try:
  117. await asyncio.wait(
  118. [incoming, outgoing],
  119. # Clean up and exit when the server closes the connection
  120. # or the user enters EOT (^D), whichever happens first.
  121. return_when=asyncio.FIRST_COMPLETED,
  122. )
  123. # asyncio.run() cancels the main task when the user triggers SIGINT (^C).
  124. # https://docs.python.org/3/library/asyncio-runner.html#handling-keyboard-interruption
  125. # Clean up and exit without re-raising CancelledError to prevent Python
  126. # from raising KeyboardInterrupt and displaying a stack track.
  127. except asyncio.CancelledError: # pragma: no cover
  128. pass
  129. finally:
  130. incoming.cancel()
  131. outgoing.cancel()
  132. transport.close()
  133. await websocket.close()
  134. assert websocket.close_code is not None and websocket.close_reason is not None
  135. close_status = Close(websocket.close_code, websocket.close_reason)
  136. print_over_input(f"Connection closed: {escape(str(close_status))}.")
  137. def main(argv: list[str] | None = None) -> None:
  138. parser = argparse.ArgumentParser(
  139. prog="websockets",
  140. description="Interactive WebSocket client.",
  141. add_help=False,
  142. )
  143. group = parser.add_mutually_exclusive_group()
  144. group.add_argument("--version", action="store_true")
  145. group.add_argument("uri", metavar="<uri>", nargs="?")
  146. args = parser.parse_args(argv)
  147. if args.version:
  148. print(f"websockets {websockets_version}")
  149. return
  150. if args.uri is None:
  151. parser.print_usage()
  152. sys.exit(2)
  153. # Enable VT100 to support ANSI escape codes in Command Prompt on Windows.
  154. # See https://github.com/python/cpython/issues/74261 for why this works.
  155. if sys.platform == "win32":
  156. os.system("")
  157. try:
  158. import readline # noqa: F401
  159. except ImportError: # readline isn't available on all platforms
  160. pass
  161. # Remove the try/except block when dropping Python < 3.11.
  162. try:
  163. asyncio.run(interactive_client(args.uri))
  164. except KeyboardInterrupt: # pragma: no cover
  165. pass