我正在用python编写一些程序,每当我故意停止程序时(从PyCharm客户端的停止按钮停止),我都希望程序在停止之前执行更多命令。停止程序时会引发异常吗?我尝试添加尝试,除了KeyboardInterrupt例外,但这没有用。
答案 0 :(得分:1)
您可以捕获KeyboardInterrupt个错误。
尝试运行该脚本并将其杀死,您将看到将打印KeyboardInterrupt happened!
:
import time
try:
time.sleep(5)
except KeyboardInterrupt:
print("KeyboardInterrupt happened!")
raise