I've been trying to write an elegant [y/n] prompt for scripts that I'll be running over command line. I came across this:
http://mattoc.com/python-yes-no-prompt-cli.html
This is the program I wrote up to test it (it really just involved changing raw_input to input as I'm using Python3):
import sys
from distutils import strtobool
def prompt(query):
sys.stdout.write("%s [y/n]: " % query)
val = input()
try:
ret = strtobool(val)
except ValueError:
sys.stdout.write("Please answer with y/n")
return prompt(query)
return ret
while True:
if prompt("Would you like to close the program?") == True:
break
else:
continue
However, whenever I try to run the code I get the following error:
ImportError: cannot import name strtobool
Changing "from distutils import strtobool" to "import distutils" doesn't help, as a NameError is raised:
Would you like to close the program? [y/n]: y
Traceback (most recent call last):
File "yes_no.py", line 15, in <module>
if prompt("Would you like to close the program?") == True:
File "yes_no.py", line 6, in prompt
val = input()
File "<string>", line 1, in <module>
NameError: name 'y' is not defined
How do I go about solving this problem?