Skip to content

Instantly share code, notes, and snippets.

@Jasata
Created April 24, 2020 11:47
Show Gist options
  • Save Jasata/b0a3387e7f46786ece351dec71d3f2d3 to your computer and use it in GitHub Desktop.
Save Jasata/b0a3387e7f46786ece351dec71d3f2d3 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
#
# Simple command line yes/no prompter.
# 2020-04-24 Jani Tammi <[email protected]>
#
# default = None | "y" | "n" If and how ENTER is interpreted.
# echo = False | True Will the prompt line be appended with selection.
#
def getch():
"""Read single character from standard input without echo."""
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
# Python 3.6+
def yn_prompt(question: str, default=None, echo=False) -> bool:
"""Prompts a Yes/No question in console and returns True ("yes") or False ("no"). Second argument ("default") has three possible values; None, "n" or "y". Strings that cannot be interpreted are considered None. Default affects how ENTER keys are interpreted."""
if default:
# Empty string is False and will not branch here
default = default[0].lower()
if default not in ("n", "y"):
default = None
opts = "y/n"
else:
opts = ("y/N", "Y/n")[int(default == 'y')]
else:
default = None
opts = "y/n"
print(f"{question} ({opts}): ", end = "", flush = True)
c = ""
while c not in ("y", "n"):
c = getch().lower()
if ord(c) == 0x0d and default:
selection = default == 'y'
break
selection = c == 'y'
if echo:
print(f"{('NO', 'YES')[int(selection)]}", flush = True)
else:
print("")
return selection
if __name__ == "__main__":
if yn_prompt("None?"):
print("yes")
else:
print("no")
if yn_prompt("empty string?", default="", echo=True):
print("yes")
else:
print("no")
if yn_prompt("gargage string?", default="garbage", echo=False):
print("yes")
else:
print("no")
if yn_prompt("yes?", default="YES", echo=True):
print("yes")
else:
print("no")
if yn_prompt("no?", default="NO", echo=True):
print("yes")
else:
print("no")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment