2017-05-05 64 views
1

我想在鍵盤中斷時執行一些bash腳本,但似乎我的python代碼退出時沒有在鍵盤中斷處執行bash腳本。這裏是我的示例代碼。在python鍵盤中斷時執行bash腳本

from flask import Flask 
import os 
#here resides my flask code 

try: 
    if __name__ == '__main__': 
     app.run() 
except (KeyboardInterrupt, SystemExit): 
    os.system('echo "running bash script from python"') 
    os.system('netstat --listen') 
    os.system('sudo service apache2 start') 
    exit() 
+1

這很奇怪。我根本沒有這個問題。無論是Python 2還是3。它是一個權限問題? – Evey

回答

0

在思考這個問題,我想你的應用程序可能會捕獲一個KeyboardInterrupt和防止封裝腳本曾經獲得異常,強行殺死進程或者類似的東西。一個我能做的再現你的問題的最小例子是:

import os 

if __name__ == '__main__': 
    try: 
     while True: 
      try: 
       pass 
      except KeyboardInterrupt: 
       os.kill(os.getpid(), 9) 
    except (KeyboardInterrupt, SystemExit): 
     os.system('echo "This will not be executed"') 
+0

您給出的示例@Evey它在退出時執行bash腳本,但它僅在echo中打印消息,但不會啓動apache2服務,儘管它顯示服務啓動的消息 –