我一直在尝试为将在命令行上运行的脚本编写一个优雅的[y/n]提示。我发现了这个:
这是我为测试它而编写的程序(它实际上只涉及到将原始输入更改为输入,因为我使用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
但是,每当我尝试运行代码时,都会出现以下错误:
^{pr2}$
将“from distutils import strtobool”更改为“import distutils”没有帮助,因为会引发名称错误:Would you like to close the program? [y/n]: y
Traceback (most recent call last):
File "yes_no.py", line 15, in
if prompt("Would you like to close the program?") == True:
File "yes_no.py", line 6, in prompt
val = input()
File "", line 1, in
NameError: name 'y' is not defined
我如何着手解决这个问题?在