python如何在中断操作(ctrl-c)后,再执行一段代码再关闭?
如题,我在写一个爬虫过程中,因为不太好预估数据量,打算设置一个直接手动停止的功能。目前想到的比较方便的办法就是捕获ctrl+C终止命令,然后利用try except方法终止。但是一个前提是在捕获中断操作后,要保存之前通过while循环获得的数据。
我写了一个测试代码,但是发现(ctrl+c中断后并不执行后续的"there it is?")
import time try:
while True:
print('yes!')
time.sleep(1)
except Exception as e:
print(e)
pass
print('there it is!')
回答:
KeyboardInterrupt:
exception
KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly. The exception inherits from
BaseException
so as to not be accidentally caught by code that catchesException
and thus prevent the interpreter from exiting.
KeyboardInterrupt
故意做成不是从 Exception
继承来的,而是来自 BaseException
,为的就是不被 execpt Exception
捕获。
你可以直接写 except KeyboardInterrupt as e:
。
以上是 python如何在中断操作(ctrl-c)后,再执行一段代码再关闭? 的全部内容, 来源链接: utcz.com/p/937760.html