3 """Utilities related to user input."""
5 import readchar # type: ignore
8 from typing import List
13 def single_keystroke_response(
14 valid_responses: List[str],
17 default_response: str = None,
18 timeout_seconds: int = None,
20 def _handle_timeout(signum, frame) -> None:
21 raise exceptions.TimeoutError()
23 def _single_keystroke_response_internal(
24 valid_responses: List[str], timeout_seconds=None
26 os_special_keystrokes = [3, 26] # ^C, ^Z
27 if timeout_seconds is not None:
28 signal.signal(signal.SIGALRM, _handle_timeout)
29 signal.alarm(timeout_seconds)
33 response = readchar.readchar()
34 if response in valid_responses:
36 if ord(response) in os_special_keystrokes:
40 if timeout_seconds is not None:
43 if prompt is not None:
47 response = _single_keystroke_response_internal(
48 valid_responses, timeout_seconds
50 except exceptions.TimeoutError:
51 if default_response is not None:
52 response = default_response
53 if prompt is not None:
58 def yn_response(prompt: str = None, *, timeout_seconds=None) -> str:
59 return single_keystroke_response(
60 ["y", "n", "Y", "N"], prompt=prompt, timeout_seconds=timeout_seconds
64 def keystroke_helper() -> None:
65 print("Watching for keystrokes; ^C to quit.")
67 key = readchar.readkey()
69 print(f'That was "{key}" ({ord(key)}).')
73 print(f'That was sequence "{key}" (', end="")
75 print(f" {ord(_)} ", end="")