如何在外壳上没有错误消息的情况下停止 Python 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/483208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:13:05  来源:igfitidea点击:

How to stop a Python script without error messages on the shell?

pythonerror-handling

提问by user46646

I want to stop a Python script on seeing an error message.
I dont want any error message on shell like exit().
How to do it ???

我想在看到错误消息时停止 Python 脚本。
我不希望像 exit() 这样的 shell 上出现任何错误消息。
怎么做 ???

回答by Gonzalo Quero

When you send CTRL+Cto a Python script, it raises the KeyboardInterruptexception, so you can do something like

当您发送CTRL+C到 Python 脚本时,它会引发KeyboardInterrupt异常,因此您可以执行以下操作

try:
    ... Work goes here ...
except KeyboardInterrupt:
    sys.exit(0)