gpt4 book ai didi

python - 是/否在 Python3 中使用 strtobool 提示

转载 作者:太空狗 更新时间:2023-10-30 02:02:21 28 4
gpt4 key购买 nike

我一直在尝试为将在命令行上运行的脚本编写优雅的 [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

但是,每当我尝试运行代码时,我都会收到以下错误:

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

我该如何解决这个问题?

最佳答案

第一条错误信息:

ImportError: 无法导入名称 strtobool

告诉您在您导入的 distutils 模块中没有公开可见的 strtobool 函数。

这是因为它在 python3 中移动了:改用 from distutils.util import strtobool

https://docs.python.org/3/distutils/apiref.html#distutils.util.strtobool


第二个错误消息让我很困惑——它似乎暗示你输入的 y 试图被解释为代码(因此提示它不知道任何 y 变量。我不太明白那是怎么发生的!

...两年过去了...

啊,我现在明白了... input 在 Python 3 中是“从键盘获取一个字符串”,但是 input 在 Python 2 中是“获取一个字符串从键盘,然后 eval 它”。假设您不想eval 输入,请改用 Python 2 上的 raw_input

关于python - 是/否在 Python3 中使用 strtobool 提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42248342/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com