Python's distutils includes a nice helper function called strtobool, handling the conversion from user-input to a boolean value. Useful for confirm/cancel prompts in command-line scripts.
Helper function:
1 2 3 4 5 6 7 8 9 10 11 | from distutils import strtobool
def prompt(query):
sys.stdout.write('%s [y/n]: ' % query)
val = raw_input()
try:
ret = strtobool(val)
except ValueError:
sys.stdout.write('Please answer with a y/n\n')
return prompt(query)
return ret
|
Usage:
1 2 | if prompt('''Hey, listen! You're about to delete all records, are you sure?'''):
mega_delete()
|