使用ctrl停止python+

2024-05-21 09:09:59 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

在Windows上,唯一可靠的方法是使用CtrlBreak。立即停止所有python脚本!

(注意,在一些键盘上,“Break”标记为“Pause”。)

如果它在Python shell中运行,请使用Ctrl+Z,否则请找到python进程并终止它。

在运行python程序时按Ctrl+c将导致python引发^{}异常。一个发出大量HTTP请求的程序可能会有大量异常处理代码。如果try-except块的except部分没有指定它应该捕获哪些异常,它将捕获所有异常,包括您刚才导致的KeyboardInterrupt。正确编码的python程序将使用python exception hierarchy,并且只捕获从Exception派生的异常。

#This is the wrong way to do things
try:
  #Some stuff might raise an IO exception
except:
  #Code that ignores errors

#This is the right way to do things
try:
  #Some stuff might raise an IO exception
except Exception:
  #This won't catch KeyboardInterrupt

如果无法更改代码(或需要终止程序以使更改生效),则可以尝试快速按Ctrl+c。第一个KeyboardInterrupt异常将把您的程序从try块中敲出,希望当程序在try块之外时,会引发后面的KeyboardInterrupt异常之一。

相关问题 更多 >