python-3.x - Python 3 键盘中断错误

标签 python-3.x ctrl keyboardinterrupt

我注意到,在任何 python 3 程序上,无论它多么基本,如果你按下 CTRL c 它都会使程序崩溃,例如:

test=input("Say hello")
if test=="hello":
    print("Hello!")
else:
    print("I don't know what to reply I am a basic program without meaning :(")

如果您按 CTRL c 错误将是 KeyboardInterrupt 有没有办法阻止程序崩溃?

我想这样做的原因是因为我喜欢让我的程序防错,每当我想将某些内容粘贴到输入中时,我不小心按了 CTRL c 我必须再次检查我的程序......这很烦人。

最佳答案

Control-C将引发 KeyboardInterrupt不管你多么不想要它。但是,您可以非常轻松地处理错误,例如,如果您想要求用户在获取输入时按两次 control-c 以退出,您可以执行以下操作:

def user_input(prompt):
    try:
        return input(prompt)
    except KeyboardInterrupt:
        print("press control-c again to quit")
    return input(prompt) #let it raise if it happens again
或者强制用户无论使用多少次都必须输入内容Control-C你可以这样做:
def user_input(prompt):
    while True: # broken by return
        try:
            return input(prompt)
        except KeyboardInterrupt:
            print("you are not allowed to quit right now")
虽然我不会推荐第二个,因为使用快捷方式的人很快就会对你的程序感到恼火。

关于python-3.x - Python 3 键盘中断错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37887624/

相关文章:

multithreading - 多线程 perl 脚本中的 Control+C 处理

python - Matplotlib ylim 和 xlim 无法与散点图和线图或 fill_ Between 组合使用

javascript - ctrl + 在 JavaScript 中点击

Python 请求 - Cookie 错误

eclipse - Eclipse的重做键盘快捷键

visual-studio-2010 - 如何更改 Visual Studio 的 ctrl+space

r - 在 R 中使用 "sink()"将写入从文件切换到标准输出

python - 为什么我的线程/多处理 python 脚本没有正常退出?

python : AttributeError: 'str' object has no attribute '1s'

python - 如何创建项目列表以在 Jinja2 模板页面上多次使用?