【发布时间】:2017-02-15 11:39:38
【问题描述】:
我一直在尝试为将在命令行上运行的脚本编写一个优雅的 [y/n] 提示符。我遇到了这个:
http://mattoc.com/python-yes-no-prompt-cli.html
这是我编写的用于测试它的程序(它实际上只是涉及在我使用 Python3 时将 raw_input 更改为 input):
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
但是,每当我尝试运行代码时,我都会收到以下错误:
ImportError: cannot import name strtobool
将“from distutils import strtobool”更改为“import distutils”没有帮助,因为引发了 NameError:
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
我该如何解决这个问题?
【问题讨论】:
-
Afaik,我从网站上取下的那段代码是用 2.x 编写的,而我试图在 3.x 中复制它
标签: python python-3.x