【问题标题】:Yes/No prompt in Python3 using strtoboolPython3 中使用 strtobool 提示是/否
【发布时间】: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


【解决方案1】:

第一条错误信息:

ImportError: cannot import name strtobool

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

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

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


第二条错误消息让我很困惑——它似乎暗示您输入的y 正试图被解释为代码(因此抱怨它不知道任何y 变量。我可以'不太清楚这是怎么发生的!

...两年过去了...

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

【讨论】:

  • 现在完美运行!我尝试“导入 distutils”,然后也在函数中使用 distutils.util.strtobool,但显然这不是正确的方法。第二个错误对我来说仍然是个谜。可能是因为我试图导入strtobool,但该功能不存在,而程序仍在尝试执行提示功能?
  • 真的不应该;除非你的代码中有eval(...) 或类似的东西,否则你的数据永远不会被执行。 (数据被执行通常是一个很大的安全问题......)
【解决方案2】:

distutils 包在 Python 3.10 中为 deprecated,将从 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,))

【讨论】:

    猜你喜欢
    • 2013-03-01
    • 2018-02-06
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 2016-09-18
    • 2013-07-15
    • 2017-12-23
    • 1970-01-01
    相关资源
    最近更新 更多