2014-01-21 76 views
4

如果我正在linux終端上運行一個python程序,並且我按下ctrl + c手動中止它,那麼如何讓我的程序在發生此事件時執行某些操作。Python-如何檢查程序是否在運行時被用戶中止?

類似:

if sys.exit(): 
    print "you chose to end the program" 
+0

你必須使用'signal'模塊。 http://stackoverflow.com/a/18115530/1688590。還要注意檢查'if sys.exit()'是否會立即關閉你的程序。 – xbello

+1

@xbello由於OP要求用'ctrl-C'退出,所以不需要信號。 'KeyboardInterrupt'就足夠了。 – FallenAngel

回答

8

你可以寫一個信號處理函數

import signal,sys 
def signal_handling(signum,frame): 
    print "you chose to end the program" 
    sys.exit() 

signal.signal(signal.SIGINT,signal_handling) 
while True: 
    pass 

按Ctrl + c發送一個SIGINT中斷,輸出:

您選擇以結束該程序

+0

爲什麼downvote? –

+0

@TimPietzcker:不,當然。這似乎是一個有效的答案,儘管人們習慣於使用'KeyBoardInterrupt'異常。 – Abhijit

+1

@Ahhijit:我認爲一個設置良好的信號處理程序比不得不將整個程序包裝在'try/except'中更好。我想這取決於如果用戶選擇*不*中止程序會發生什麼。 –

1

檢查KeyboardInterrupt例外Python編寫的。

您可以將您的代碼放入try區塊,用except捕獲KeyboardInterrupt例外並讓用戶知道他已退出。

6

好了,你可以使用KeyBoardInterrupt,使用try-except塊:

try: 
    # some code here 
except KeyboardInterrupt: 
    print "You exited 

嘗試在你的命令行:

import time 

try: 
    while True: 
     time.sleep(1) 
     print "Hello" 
except KeyboardInterrupt: 
    print "No more Hellos" 
相關問題