2013-12-08 26 views
2

當我按CTRL + C取消正在運行的Python腳本時,是否有腳本終止前運行某個python代碼的方法?當取消Python腳本時,做點什麼

+1

您可以趕上'KeyboardInterrupt'錯誤;或者你可以設置[信號處理程序](http://stackoverflow.com/a/1112350/344643);或者你可以在退出時做些事情[使用atexit模塊](http://docs.python.org/2/library/atexit.html#atexit-example)。 –

回答

6

使用try/except捕捉要KeyboardInterrupt,這是引發當您按下CTRL +Ç

這是一個基本的腳本來演示:

try: 
    # Main code 
    while True: 
     print 'hi!' 
except KeyboardInterrupt: 
    # Cleanup/exiting code 
    print 'done!' 

這將持續打印'hi!'直到你按下CTRL +Ç。然後,它打印'done!'並退出。

0
try: 
    # something 
except KeyboardInterrupt: 
    # your code after ctrl+c 
1

CTRL + C提高KeyboardInterrupt。你可以捕捉它就像任何其他異常:

try: 
    main() 
except KeyboardInterrupt: 
    cleanup() 

如果你真的不喜歡,你還可以使用atexit.register註冊清理操作運行(前提是你不要做一些令人頭痛和原因解釋退出的一個時髦的方式)

+0

'atexit.register'是一個很好的選擇。 – SethMMorton

0

此代碼

import time 

try: 
    while True: 
     time.sleep(2) 
except KeyboardInterrupt: 
    print "Any clean" 

[email protected] ~/tmp $ python test.py 
^CAny clean 

當我執行時按Ctrl+C
你只需要處理KeyboardInterrupt異常。

此外,你可以處理signals設置處理程序。

0

我很確定你只需要一個try/finally塊。

試試這個腳本:

import time 

def main(): 
    try: 
     while True: 
      print("blah blah") 
      time.sleep(5) 
    except KeyboardInterrupt: 
     print("caught CTRL-C") 
    finally: 
     print("do cleanup") 

if __name__ == '__main__': 
    main() 

輸出應該是這樣的:

blah blah 
caught CTRL-C 
do cleanup