我一直在尝试为脚本写一个优雅的[y/n]提示符,我将通过命令行运行.我遇到了这个:
http://mattoc.com/python-yes-no-prompt-cli.html
这是我编写的用于测试它的程序(它实际上只涉及将raw_input更改为输入,因为我正在使用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
Run Code Online (Sandbox Code Playgroud)
但是,每当我尝试运行代码时,我都会收到以下错误:
ImportError: cannot import name strtobool
Run Code Online (Sandbox Code Playgroud)
将"从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
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
Eug*_*ash 12
该distutils包已在 Python 3.10 中弃用,并将从 Python 3.12 中删除。幸运的是,该strtobool函数非常小,因此您只需将其代码复制到您的模块即可:
def strtobool(val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on', '1'):
return 1
elif val in ('n', 'no', 'f', 'false', 'off', '0'):
return 0
else:
raise ValueError("invalid truth value %r" % (val,))
Run Code Online (Sandbox Code Playgroud)
第一条错误消息:
ImportError: cannot import name strtobool
告诉你,你导入strtobool的distutils模块中没有公开可见的功能.
这是因为它在python3中移动:改为使用from distutils.util import strtobool.
https://docs.python.org/3/distutils/apiref.html#distutils.util.strtobool
第二条错误信息让我感到非常困惑 - 这似乎意味着y你输入的内容正在尝试被解释为代码(并因此抱怨它不知道任何y变量.我不太明白这是怎么发生的!