Skip to content

Instantly share code, notes, and snippets.

@jamescherti
Last active December 25, 2022 22:07
Show Gist options
  • Save jamescherti/1f7d9adc428db00f9104312a24537d52 to your computer and use it in GitHub Desktop.
Save jamescherti/1f7d9adc428db00f9104312a24537d52 to your computer and use it in GitHub Desktop.
Python: Ask the user a yes/no question.
#!/usr/bin/env python
# License: MIT
# Author: James Cherti
# URL: https://gist.github.com/jamescherti/1f7d9adc428db00f9104312a24537d52
"""Ask the user a yes/no question."""
import sys
import signal
import select
def ask_question(question: str, timeout: int = 0) -> bool:
"""Ask the user a yes/no question."""
# Empty stdin
while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = sys.stdin.readline()
if not line:
# stdin is empty
break
if timeout > 0:
def alarm_handler(signum, frame):
"""SIGALRM handler."""
raise TimeoutError
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(timeout)
try:
while True:
try:
answer = input("{} [y, n] ".format(question))
except (EOFError, KeyboardInterrupt):
# Ignore EOF (CTRL-D) and SIGINT (CTRL-C)
answer = ""
answer = answer.strip()
if answer == "y":
return True
elif answer == "n":
return False
else:
answer = ""
finally:
if timeout > 0:
signal.alarm(0) # cancel the alarm
if __name__ == '__main__':
try:
print(ask_question("Are you sure? (you have 10 seconds)", timeout=10))
except TimeoutError:
print()
print("Timeout!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment