import time
try:
while True:
print('press Ctrl-C to stop')
time.sleep(1)
finally:
print('\n\nCleanup code is here\n')
$ python cleanup.py
press Ctrl-C to stop
press Ctrl-C to stop
press Ctrl-C to stop
^C
Cleanup code is here
Traceback (most recent call last):
File "cleanup.py", line 7, in <module>
time.sleep(1)
KeyboardInterrupt
您可以处理KeyboardInterrupt它,以便异常不会破坏程序结束时的情绪:
import time
try:
while True:
print('press Ctrl-C to stop')
time.sleep(1)
except KeyboardInterrupt:
print('\n\nKeyboardInterrupt cleanup code is here')
finally:
print('\n\nCommon cleanup code is here')
$ python cleanup.py
press Ctrl-C to stop
press Ctrl-C to stop
press Ctrl-C to stop
^C
KeyboardInterrupt cleanup code is here
Common cleanup code is here
使用
try/finally
. 即使发生异常,finally
也会执行该块:您可以处理
KeyboardInterrupt
它,以便异常不会破坏程序结束时的情绪: