取消Python脚本时会做一些事情

Joh*_*ohn 2 python

当我按CTRL + C取消正在运行的python脚本时,有没有办法在脚本终止之前运行某个python代码?

iCo*_*dez 6

使用try/except捕捉到的KeyboardInterrupt,当你按下它提出CTRL+ C.

这是一个演示的基本脚本:

try:
    # Main code
    while True:
        print 'hi!'
except KeyboardInterrupt:
    # Cleanup/exiting code
    print 'done!'
Run Code Online (Sandbox Code Playgroud)

这将持续打印,'hi!'直到您按CTRL+ C.然后,它打印'done!'并退出.