使用strtobool在Python3中是/否提示
我一直在尝试为脚本写一个优雅的[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 将“从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中移动:使用来自distutils.util import strtobool. https://docs.python.org/3/distutils/apiref.html#distutils.util.strtobool 第二条错误信息让我深感困惑 – 这似乎意味着你输入的y试图被解释为代码(并因此抱怨它不知道任何y变量.我不太明白这是怎么回事发生! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |