使用 Ctrl-C 删除 Python 中的回溯
有没有办法在您按 Ctrl+c 时阻止回溯出现, 即在Python脚本中引发KeyboardInterrupt
?
Is there a way to keep tracebacks from coming up when you hit Ctrl+c,
i.e. raise KeyboardInterrupt
in a Python script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
试试这个:
这样您就不需要将所有内容都包装在异常处理程序中。
Try this:
This way you don't need to wrap everything in an exception handler.
这是最简单的方法,假设您在按下 Ctrl+c 时仍想退出。
如果你想在不尝试/例外的情况下捕获它,你可以使用 像这样的配方使用
signal
模块,除了它似乎在 Windows 上对我不起作用..Is the simplest way, assuming you still want to exit when you get a Ctrl+c.
If you want to trap it without a try/except, you can use a recipe like this using the
signal
module, except it doesn't seem to work for me on Windows..根据 正确处理 SIGINT/SIGQUIT,唯一的方法如果您捕获到 SIGINT,正确退出就是随后用 SIGINT 信号杀死自己(请参阅标题为“如何成为一个正确的程序”的部分)。尝试伪造正确的退出代码是不正确的。有关详细信息,另请检查 为什么“执行 exit 130 与死于 SIGINT 不同”? 在 Unix Stack Exchange 上。
似乎这里所有退出零的答案实际上都表明程序行为不当。最好不要隐藏您被中断的情况,以便调用者(通常是 shell)知道该怎么做。
在 Python 中,stderr 上的回溯打印输出来自默认的
sys。 excepthook
行为。因此,为了抑制回溯垃圾邮件,我选择通过替换键盘中断上的 except 钩子来直接解决问题,然后通过重新引发原始异常来保留正确的退出代码:结果如下:
如果您没有任何要执行的清理操作,并且您想要做的就是禁止在中断时打印回溯,那么默认安装它可能会更简单:
According to Proper handling of SIGINT/SIGQUIT, the only way to exit correctly if you're catching a SIGINT is to subsequently kill yourself with a SIGINT signal (see the section titled "How to be a proper program"). It is incorrect to attempt to fake the proper exit code. For more info about that, check also Why is "Doing an exit 130 is not the same as dying of SIGINT"? over on Unix Stack Exchange.
It seems all the answers here which are exiting zero actually demonstrate programs that misbehave. It's preferable not to hide that you were interrupted, so that the caller (usually a shell) knows what to do.
In Python, the traceback printout on stderr comes from the default
sys.excepthook
behaviour. So, to suppress the traceback spam, I've opted to tackle the problem directly at the cause by replacing the except hook on keyboard interrupt, and then preserve the correct exit code by re-raising the original exception:The result is like this:
If you don't have any cleanup actions to execute, and all you wanted to do is suppress printing the traceback on interrupt, it may be simpler just to install that by default:
捕获
KeyboardInterrupt
:Catch the
KeyboardInterrupt
:用 try/ except 块捕获它:
Catch it with a try/except block:
另请注意,默认情况下,解释器退出时状态码为 128 + 您平台上的 SIGINT 值(在大多数系统上为 2)。
Also note that by default the interpreter exits with the status code 128 + the value of SIGINT on your platform (which is 2 on most systems).
使用上下文管理器抑制异常:
suppress exception using context manager: