Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是在I';我要停止这个节目?_Python_Exception_Keyboardinterrupt - Fatal编程技术网

Python 是在I';我要停止这个节目?

Python 是在I';我要停止这个节目?,python,exception,keyboardinterrupt,Python,Exception,Keyboardinterrupt,我正在用python编写一些程序,每当我仔细地停止程序时(从PyCharm客户端的停止按钮),我希望程序在停止之前执行更多的命令。当我停止程序时是否引发异常?我试图添加一个try,除了KeyboardInterrupt异常,但没有成功。您可以捕获错误 试着运行这个脚本并杀死它,你会看到键盘中断发生了将被打印: import time try: time.sleep(5) except KeyboardInterrupt: print("KeyboardInterrupt happ

我正在用python编写一些程序,每当我仔细地停止程序时(从PyCharm客户端的停止按钮),我希望程序在停止之前执行更多的命令。当我停止程序时是否引发异常?我试图添加一个try,除了KeyboardInterrupt异常,但没有成功。

您可以捕获错误

试着运行这个脚本并杀死它,你会看到
键盘中断发生了将被打印:

import time
try:
    time.sleep(5)
except KeyboardInterrupt:
    print("KeyboardInterrupt happened!")
    raise

建议你看看这个模块——这可能会让你的问题变得毫无意义。正如我在问题中所说的,我已经试过了,但由于某种原因,这个模块不起作用。也许IntelliJ停止程序的方式不同,没有使用键盘中断?奇怪的是,它在Pycharm中对我有效。您是否尝试捕获
SystemExit
-
除了(键盘中断,SystemExit):
仍然无法工作。感谢您让我熟悉捕获多个异常的语法:)