_termui_impl.py
This file
Path
src/click/_termui_impl.py
909 lines · 29.2 KiB · Python
Last changed by
Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
History of this fileTake it
1"""2This module contains implementations for the termui module. To keep the3import time of Click down, some infrequently used functionality is4placed in this module and only imported as needed.5"""67from __future__ import annotations89import collections.abc as cabc10import contextlib11import io12import math13import os14import shlex15import sys16import time17import typing as t18from gettext import gettext as _19from io import StringIO20from pathlib import Path21from types import TracebackType2223from ._compat import _default_text_stdout24from ._compat import CYGWIN25from ._compat import get_best_encoding26from ._compat import isatty27from ._compat import strip_ansi28from ._compat import term_len29from ._compat import WIN30from .exceptions import ClickException31from .utils import echo3233V = t.TypeVar("V")343536class _BufferedTextPagerStream(t.Protocol):37 buffer: t.BinaryIO383940def _has_binary_buffer(41 stream: t.BinaryIO | t.TextIO,42) -> t.TypeGuard[_BufferedTextPagerStream]:43 # TextIO is wider than TextIOWrapper; text-only streams such as StringIO44 # are valid TextIO values but do not expose a binary buffer to wrap.45 return getattr(stream, "buffer", None) is not None464748if os.name == "nt":49 BEFORE_BAR = "\r"50 AFTER_BAR = "\n"51else:52 BEFORE_BAR = "\r\033[?25l"53 AFTER_BAR = "\033[?25h\n"545556class ProgressBar(t.Generic[V]):57 def __init__(58 self,59 iterable: cabc.Iterable[V] | None,60 length: int | None = None,61 fill_char: str = "#",62 empty_char: str = " ",63 bar_template: str = "%(bar)s",64 info_sep: str = " ",65 hidden: bool = False,66 show_eta: bool = True,67 show_percent: bool | None = None,68 show_pos: bool = False,69 item_show_func: t.Callable[[V | None], str | None] | None = None,70 label: str | None = None,71 file: t.TextIO | None = None,72 color: bool | None = None,73 update_min_steps: int = 1,74 width: int = 30,75 ) -> None:76 self.fill_char = fill_char77 self.empty_char = empty_char78 self.bar_template = bar_template79 self.info_sep = info_sep80 self.hidden = hidden81 self.show_eta = show_eta82 self.show_percent = show_percent83 self.show_pos = show_pos84 self.item_show_func = item_show_func85 self.label: str = label or ""8687 if file is None:88 file = _default_text_stdout()8990 # There are no standard streams attached to write to. For example,91 # pythonw on Windows.92 if file is None:93 file = StringIO()9495 self.file = file96 self.color = color97 self.update_min_steps = update_min_steps98 self._completed_intervals = 099 self.width: int = width100 self.autowidth: bool = width == 0101102 if length is None:103 from operator import length_hint104105 length = length_hint(iterable, -1)106107 if length == -1:108 length = None109 if iterable is None:110 if length is None:111 raise TypeError("iterable or length is required")112 iterable = t.cast("cabc.Iterable[V]", range(length))113 self.iter: cabc.Iterable[V] = iter(iterable)114 self.length = length115 self.pos: int = 0116 self.avg: list[float] = []117 self.last_eta: float118 self.start: float119 self.start = self.last_eta = time.time()120 self.eta_known: bool = False121 self.finished: bool = False122 self.max_width: int | None = None123 self.entered: bool = False124 self.current_item: V | None = None125 self._is_atty = isatty(self.file)126 self._last_line: str | None = None127128 def __enter__(self) -> ProgressBar[V]:129 self.entered = True130 self.render_progress()131 return self132133 def __exit__(134 self,135 exc_type: type[BaseException] | None,136 exc_value: BaseException | None,137 tb: TracebackType | None,138 ) -> None:139 self.render_finish()140141 def __iter__(self) -> cabc.Iterator[V]:142 if not self.entered:143 raise RuntimeError("You need to use progress bars in a with block.")144 self.render_progress()145 return self.generator()146147 def __next__(self) -> V:148 # Iteration is defined in terms of a generator function,149 # returned by iter(self); use that to define next(). This works150 # because `self.iter` is an iterable consumed by that generator,151 # so it is re-entry safe. Calling `next(self.generator())`152 # twice works and does "what you want".153 return next(iter(self))154155 def render_finish(self) -> None:156 if self.hidden or not self._is_atty:157 return158 self.file.write(AFTER_BAR)159 self.file.flush()160161 @property162 def pct(self) -> float:163 if self.finished:164 return 1.0165 return min(self.pos / (float(self.length or 1) or 1), 1.0)166167 @property168 def time_per_iteration(self) -> float:169 if not self.avg:170 return 0.0171 return sum(self.avg) / float(len(self.avg))172173 @property174 def eta(self) -> float:175 if self.length is not None and not self.finished:176 return self.time_per_iteration * (self.length - self.pos)177 return 0.0178179 def format_eta(self) -> str:180 if self.eta_known:181 t = int(self.eta)182 seconds = t % 60183 t //= 60184 minutes = t % 60185 t //= 60186 hours = t % 24187 t //= 24188 if t > 0:189 return "{d}{day_label} {h:02}:{m:02}:{s:02}".format(190 d=t,191 day_label=_("d"),192 h=hours,193 m=minutes,194 s=seconds,195 )196 else:197 return f"{hours:02}:{minutes:02}:{seconds:02}"198 return ""199200 def format_pos(self) -> str:201 pos = str(self.pos)202 if self.length is not None:203 pos += f"/{self.length}"204 return pos205206 def format_pct(self) -> str:207 return f"{int(self.pct * 100): 4}%"[1:]208209 def format_bar(self) -> str:210 if self.length is not None:211 bar_length = int(self.pct * self.width)212 bar = self.fill_char * bar_length213 bar += self.empty_char * (self.width - bar_length)214 elif self.finished:215 bar = self.fill_char * self.width216 else:217 chars = list(self.empty_char * (self.width or 1))218 if self.time_per_iteration != 0:219 chars[220 int(221 (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)222 * self.width223 )224 ] = self.fill_char225 bar = "".join(chars)226 return bar227228 def format_progress_line(self) -> str:229 show_percent = self.show_percent230231 info_bits = []232 if self.length is not None and show_percent is None:233 show_percent = not self.show_pos234235 if self.show_pos:236 info_bits.append(self.format_pos())237 if show_percent:238 info_bits.append(self.format_pct())239 if self.show_eta and self.eta_known and not self.finished:240 info_bits.append(self.format_eta())241 if self.item_show_func is not None:242 item_info = self.item_show_func(self.current_item)243 if item_info is not None:244 info_bits.append(item_info)245246 return (247 self.bar_template248 % {249 "label": self.label,250 "bar": self.format_bar(),251 "info": self.info_sep.join(info_bits),252 }253 ).rstrip()254255 def render_progress(self) -> None:256 if self.hidden:257 return258259 if not self._is_atty:260 # Only output the label once if the output is not a TTY.261 if self._last_line != self.label:262 self._last_line = self.label263 echo(self.label, file=self.file, color=self.color)264 return265266 buf = []267 # Update width in case the terminal has been resized268 if self.autowidth:269 import shutil270271 old_width = self.width272 self.width = 0273 clutter_length = term_len(self.format_progress_line())274 new_width = max(0, shutil.get_terminal_size().columns - clutter_length)275 if new_width < old_width and self.max_width is not None:276 buf.append(BEFORE_BAR)277 buf.append(" " * self.max_width)278 self.max_width = new_width279 self.width = new_width280281 clear_width = self.width282 if self.max_width is not None:283 clear_width = self.max_width284285 buf.append(BEFORE_BAR)286 line = self.format_progress_line()287 line_len = term_len(line)288 if self.max_width is None or self.max_width < line_len:289 self.max_width = line_len290291 buf.append(line)292 buf.append(" " * (clear_width - line_len))293 line = "".join(buf)294 # Render the line only if it changed.295296 if line != self._last_line:297 self._last_line = line298 echo(line, file=self.file, color=self.color, nl=False)299 self.file.flush()300301 def make_step(self, n_steps: int) -> None:302 self.pos += n_steps303 if self.length is not None and self.pos >= self.length:304 self.finished = True305306 if (time.time() - self.last_eta) < 1.0:307 return308309 self.last_eta = time.time()310311 # self.avg is a rolling list of length <= 7 of steps where steps are312 # defined as time elapsed divided by the total progress through313 # self.length.314 if self.pos:315 step = (time.time() - self.start) / self.pos316 else:317 step = time.time() - self.start318319 self.avg = self.avg[-6:] + [step]320321 self.eta_known = self.length is not None322323 def update(self, n_steps: int, current_item: V | None = None) -> None:324 """Update the progress bar by advancing a specified number of325 steps, and optionally set the ``current_item`` for this new326 position.327328 :param n_steps: Number of steps to advance.329 :param current_item: Optional item to set as ``current_item``330 for the updated position.331332 .. versionchanged:: 8.0333 Added the ``current_item`` optional parameter.334335 .. versionchanged:: 8.0336 Only render when the number of steps meets the337 ``update_min_steps`` threshold.338 """339 if current_item is not None:340 self.current_item = current_item341342 self._completed_intervals += n_steps343344 if self._completed_intervals >= self.update_min_steps:345 self.make_step(self._completed_intervals)346 self.render_progress()347 self._completed_intervals = 0348349 def finish(self) -> None:350 self.eta_known = False351 self.current_item = None352 self.finished = True353354 def generator(self) -> cabc.Iterator[V]:355 """Return a generator which yields the items added to the bar356 during construction, and updates the progress bar *after* the357 yielded block returns.358 """359 # WARNING: the iterator interface for `ProgressBar` relies on360 # this and only works because this is a simple generator which361 # doesn't create or manage additional state. If this function362 # changes, the impact should be evaluated both against363 # `iter(bar)` and `next(bar)`. `next()` in particular may call364 # `self.generator()` repeatedly, and this must remain safe in365 # order for that interface to work.366 if not self.entered:367 raise RuntimeError("You need to use progress bars in a with block.")368369 if not self._is_atty:370 yield from self.iter371 else:372 for rv in self.iter:373 self.current_item = rv374375 # This allows show_item_func to be updated before the376 # item is processed. Only trigger at the beginning of377 # the update interval.378 if self._completed_intervals == 0:379 self.render_progress()380381 yield rv382 self.update(1)383384 self.finish()385 self.render_progress()386387388class MaybeStripAnsi(io.TextIOWrapper):389 def __init__(self, stream: t.IO[bytes], *, color: bool, **kwargs: t.Any):390 super().__init__(stream, **kwargs)391 self.color = color392393 def write(self, text: str) -> int:394 if not self.color:395 text = strip_ansi(text)396 return super().write(text)397398399def _pager_contextmanager(400 color: bool | None = None,401) -> t.ContextManager[tuple[t.BinaryIO | t.TextIO, str, bool]]:402 """Decide what method to use for paging through text."""403 stdout = _default_text_stdout()404405 # There are no standard streams attached to write to. For example,406 # pythonw on Windows.407 if stdout is None:408 stdout = StringIO()409410 if not isatty(sys.stdin) or not isatty(stdout):411 return _nullpager(stdout, color)412413 # Split using POSIX mode (the default) so that quote characters are414 # stripped from tokens and quoted Windows paths are preserved.415 # Non-POSIX mode retains quotes in tokens, and wrapping tokens416 # with shlex.quote re-introduces quoting issues on Windows.417 pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""))418 if pager_cmd_parts:419 if WIN:420 return _tempfilepager(pager_cmd_parts, color)421 return _pipepager(pager_cmd_parts, color)422423 if os.environ.get("TERM") in ("dumb", "emacs"):424 return _nullpager(stdout, color)425 if WIN or sys.platform.startswith("os2"):426 return _tempfilepager(["more"], color)427 return _pipepager(["less"], color)428429430@contextlib.contextmanager431def get_pager_file(color: bool | None = None) -> t.Generator[t.TextIO, None, None]:432 """Context manager.433 Yields a writable file-like object which can be used as an output pager.434 .. versionadded:: 8.4435 :param color: controls if the pager supports ANSI colors or not. The436 default is autodetection.437 """438 with _pager_contextmanager(color=color) as (stream, encoding, color):439 # Split streams by capabilities rather than the abstract TextIO /440 # BinaryIO annotations: buffered text streams can be unwrapped to bytes,441 # while text-only streams are yielded as-is.442 if _has_binary_buffer(stream):443 # Text stream backed by a binary buffer.444 stream = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)445 elif isinstance(stream, t.BinaryIO):446 # Binary stream447 stream = MaybeStripAnsi(stream, color=color, encoding=encoding)448 try:449 yield stream450 finally:451 stream.flush()452453454@contextlib.contextmanager455def _pipepager(456 cmd_parts: list[str], color: bool | None = None457) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]:458 """Page through text by feeding it to another program.459460 Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list461 produced by :func:`shlex.split`. The command is resolved to an absolute462 path with :func:`shutil.which` as recommended by the463 :mod:`subprocess` docs for Windows compatibility.464465 Invoking a pager through this might support colors: if piping to466 ``less`` and the user hasn't decided on colors, ``LESS=-R`` is set467 automatically.468 """469 # Split the command into the invoked CLI and its parameters.470 if not cmd_parts:471 stdout = _default_text_stdout() or StringIO()472 yield stdout, "utf-8", False473 return474475 import shutil476477 cmd = cmd_parts[0]478 cmd_params = cmd_parts[1:]479480 cmd_filepath = shutil.which(cmd)481 if not cmd_filepath:482 stdout = _default_text_stdout() or StringIO()483 yield stdout, "utf-8", False484 return485486 # Produces a normalized absolute path string.487 # multi-call binaries such as busybox derive their identity from the symlink488 # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)489 cmd_path = Path(cmd_filepath).absolute()490 cmd_name = cmd_path.name491492 import subprocess493494 # Make a local copy of the environment to not affect the global one.495 env = dict(os.environ)496497 # If we're piping to less and the user hasn't decided on colors, we enable498 # them by default we find the -R flag in the command line arguments.499 if color is None and cmd_name == "less":500 less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}"501 if not less_flags:502 env["LESS"] = "-R"503 color = True504 elif "r" in less_flags or "R" in less_flags:505 color = True506507 if color is None:508 color = False509510 c = subprocess.Popen(511 [str(cmd_path)] + cmd_params,512 shell=False,513 stdin=subprocess.PIPE,514 env=env,515 errors="replace",516 text=True,517 )518 stdin = t.cast(t.BinaryIO, c.stdin)519 encoding = get_best_encoding(stdin)520 try:521 yield stdin, encoding, color522 except BrokenPipeError:523 # In case the pager exited unexpectedly, ignore the broken pipe error.524 pass525 except Exception as e:526 # In case there is an exception we want to close the pager immediately527 # and let the caller handle it.528 # Otherwise the pager will keep running, and the user may not notice529 # the error message, or worse yet it may leave the terminal in a broken state.530 c.terminate()531 raise e532 finally:533 # We must close stdin and wait for the pager to exit before we continue534 try:535 stdin.close()536 # Close implies flush, so it might throw a BrokenPipeError if the pager537 # process exited already.538 except BrokenPipeError:539 pass540541 # Less doesn't respect ^C, but catches it for its own UI purposes (aborting542 # search or other commands inside less).543 #544 # That means when the user hits ^C, the parent process (click) terminates,545 # but less is still alive, paging the output and messing up the terminal.546 #547 # If the user wants to make the pager exit on ^C, they should set548 # `LESS='-K'`. It's not our decision to make.549 while True:550 try:551 c.wait()552 except KeyboardInterrupt:553 pass554 else:555 break556557558@contextlib.contextmanager559def _tempfilepager(560 cmd_parts: list[str], color: bool | None = None561) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]:562 """Page through text by invoking a program on a temporary file.563564 Used as the primary pager strategy on Windows (where piping to565 ``more`` adds spurious ``\\r\\n``), and as a fallback on other566 platforms. The command is resolved to an absolute path with567 :func:`shutil.which`.568 """569 # Split the command into the invoked CLI and its parameters.570 if not cmd_parts:571 stdout = _default_text_stdout() or StringIO()572 yield stdout, "utf-8", False573 return574575 import shutil576 import subprocess577578 cmd = cmd_parts[0]579580 cmd_filepath = shutil.which(cmd)581 if not cmd_filepath:582 stdout = _default_text_stdout() or StringIO()583 yield stdout, "utf-8", False584 return585586 # Produces a normalized absolute path string.587 # multi-call binaries such as busybox derive their identity from the symlink588 # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)589 cmd_path = Path(cmd_filepath).absolute()590591 import tempfile592593 encoding = get_best_encoding(sys.stdout)594 if color is None:595 color = False596 # On Windows, NamedTemporaryFile cannot be opened by another process597 # while Python still has it open, so we use delete=False and clean up manually598 # rather than using a contextmanager here.599 f = tempfile.NamedTemporaryFile(mode="wb", delete=False)600 try:601 yield t.cast(t.BinaryIO, f), encoding, color602 f.flush()603 f.close()604 subprocess.call([str(cmd_path), f.name])605 finally:606 os.unlink(f.name)607608609@contextlib.contextmanager610def _nullpager(611 stream: t.TextIO, color: bool | None = None612) -> t.Iterator[tuple[t.TextIO, str, bool]]:613 """Simply print unformatted text. This is the ultimate fallback."""614 encoding = get_best_encoding(stream)615 if color is None:616 color = False617 yield stream, encoding, color618619620class Editor:621 def __init__(622 self,623 editor: str | None = None,624 env: cabc.Mapping[str, str] | None = None,625 require_save: bool = True,626 extension: str = ".txt",627 ) -> None:628 self.editor = editor629 self.env = env630 self.require_save = require_save631 self.extension = extension632633 def get_editor(self) -> str:634 if self.editor is not None:635 return self.editor636 for key in "VISUAL", "EDITOR":637 rv = os.environ.get(key)638 if rv:639 return rv640 if WIN:641 return "notepad"642643 from shutil import which644645 for editor in "sensible-editor", "vim", "nano":646 if which(editor) is not None:647 return editor648 return "vi"649650 def edit_files(self, filenames: cabc.Iterable[str]) -> None:651 """Open files in the user's editor."""652 import shlex653 import subprocess654655 editor = self.get_editor()656 environ: dict[str, str] | None = None657658 if self.env:659 environ = os.environ.copy()660 environ.update(self.env)661662 try:663 # Split in POSIX mode (the default) for the same reasons as664 # in pager(): strips quotes from tokens and preserves quoted665 # Windows paths.666 c = subprocess.Popen(667 args=shlex.split(editor) + list(filenames),668 env=environ,669 )670 exit_code = c.wait()671 if exit_code != 0:672 raise ClickException(673 _("{editor}: Editing failed").format(editor=editor)674 )675 except OSError as e:676 raise ClickException(677 _("{editor}: Editing failed: {e}").format(editor=editor, e=e)678 ) from e679680 @t.overload681 def edit(self, text: bytes | bytearray) -> bytes | None: ...682683 # We cannot know whether or not the type expected is str or bytes when None684 # is passed, so str is returned as that was what was done before.685 @t.overload686 def edit(self, text: str | None) -> str | None: ...687688 def edit(self, text: str | bytes | bytearray | None) -> str | bytes | None:689 import tempfile690691 if text is None:692 data: bytes | bytearray = b""693 elif isinstance(text, (bytes, bytearray)):694 data = text695 else:696 if text and not text.endswith("\n"):697 text += "\n"698699 if WIN:700 data = text.replace("\n", "\r\n").encode("utf-8-sig")701 else:702 data = text.encode("utf-8")703704 fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)705 f: t.BinaryIO706707 try:708 with os.fdopen(fd, "wb") as f:709 f.write(data)710711 # If the filesystem resolution is 1 second, like Mac OS712 # 10.12 Extended, or 2 seconds, like FAT32, and the editor713 # closes very fast, require_save can fail. Set the modified714 # time to be 2 seconds in the past to work around this.715 os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2))716 # Depending on the resolution, the exact value might not be717 # recorded, so get the new recorded value.718 timestamp = os.path.getmtime(name)719720 self.edit_files((name,))721722 if self.require_save and os.path.getmtime(name) == timestamp:723 return None724725 with open(name, "rb") as f:726 rv = f.read()727728 if isinstance(text, (bytes, bytearray)):729 return rv730731 return rv.decode("utf-8-sig").replace("\r\n", "\n")732 finally:733 os.unlink(name)734735736def open_url(url: str, wait: bool = False, locate: bool = False) -> int:737 import subprocess738739 def _unquote_file(url: str) -> str:740 from urllib.parse import unquote741742 if url.startswith("file://"):743 url = unquote(url[7:])744745 return url746747 if sys.platform == "darwin":748 args = ["open"]749 if wait:750 args.append("-W")751 if locate:752 args.append("-R")753 args.append(_unquote_file(url))754 null = open("/dev/null", "w")755 try:756 return subprocess.Popen(args, stderr=null).wait()757 finally:758 null.close()759 elif WIN:760 if locate:761 url = _unquote_file(url)762 args = ["explorer", f"/select,{url}"]763 try:764 return subprocess.call(args)765 except OSError:766 return 127767 else:768 try:769 os.startfile(url) # type: ignore[attr-defined]770 except OSError:771 return 127772 return 0773 elif CYGWIN:774 if locate:775 url = _unquote_file(url)776 args = ["cygstart", os.path.dirname(url)]777 else:778 args = ["cygstart"]779 if wait:780 args.append("-w")781 args.append(url)782 try:783 return subprocess.call(args)784 except OSError:785 # Command not found786 return 127787788 try:789 if locate:790 url = os.path.dirname(_unquote_file(url)) or "."791 else:792 url = _unquote_file(url)793 c = subprocess.Popen(["xdg-open", url])794 if wait:795 return c.wait()796 return 0797 except OSError:798 if url.startswith(("http://", "https://")) and not locate and not wait:799 import webbrowser800801 webbrowser.open(url)802 return 0803 return 1804805806def _translate_ch_to_exc(ch: str) -> None:807 if ch == "\x03":808 raise KeyboardInterrupt()809810 if ch == "\x04" and not WIN: # Unix-like, Ctrl+D811 raise EOFError()812813 if ch == "\x1a" and WIN: # Windows, Ctrl+Z814 raise EOFError()815816817if sys.platform == "win32":818 import msvcrt819820 @contextlib.contextmanager821 def raw_terminal() -> cabc.Iterator[int]:822 yield -1823824 def getchar(echo: bool) -> str:825 # The function `getch` will return a bytes object corresponding to826 # the pressed character. Since Windows 10 build 1803, it will also827 # return \x00 when called a second time after pressing a regular key.828 #829 # `getwch` does not share this probably-bugged behavior. Moreover, it830 # returns a Unicode object by default, which is what we want.831 #832 # Either of these functions will return \x00 or \xe0 to indicate833 # a special key, and you need to call the same function again to get834 # the "rest" of the code. The fun part is that \u00e0 is835 # "latin small letter a with grave", so if you type that on a French836 # keyboard, you _also_ get a \xe0.837 # E.g., consider the Up arrow. This returns \xe0 and then \x48. The838 # resulting Unicode string reads as "a with grave" + "capital H".839 # This is indistinguishable from when the user actually types840 # "a with grave" and then "capital H".841 #842 # When \xe0 is returned, we assume it's part of a special-key sequence843 # and call `getwch` again, but that means that when the user types844 # the \u00e0 character, `getchar` doesn't return until a second845 # character is typed.846 # The alternative is returning immediately, but that would mess up847 # cross-platform handling of arrow keys and others that start with848 # \xe0. Another option is using `getch`, but then we can't reliably849 # read non-ASCII characters, because return values of `getch` are850 # limited to the current 8-bit codepage.851 #852 # Anyway, Click doesn't claim to do this Right(tm), and using `getwch`853 # is doing the right thing in more situations than with `getch`.854855 if echo:856 func = t.cast(t.Callable[[], str], msvcrt.getwche)857 else:858 func = t.cast(t.Callable[[], str], msvcrt.getwch)859860 rv = func()861862 if rv in ("\x00", "\xe0"):863 # \x00 and \xe0 are control characters that indicate special key,864 # see above.865 rv += func()866867 _translate_ch_to_exc(rv)868 return rv869870else:871 import termios872 import tty873874 @contextlib.contextmanager875 def raw_terminal() -> cabc.Iterator[int]:876 f: t.TextIO | None877 fd: int878879 if not isatty(sys.stdin):880 f = open("/dev/tty")881 fd = f.fileno()882 else:883 fd = sys.stdin.fileno()884 f = None885886 try:887 old_settings = termios.tcgetattr(fd)888889 try:890 tty.setraw(fd)891 yield fd892 finally:893 termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)894 sys.stdout.flush()895896 if f is not None:897 f.close()898 except termios.error:899 pass900901 def getchar(echo: bool) -> str:902 with raw_terminal() as fd:903 ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")904905 if echo and isatty(sys.stdout):906 sys.stdout.write(ch)907908 _translate_ch_to_exc(ch)909 return ch