1

I want to execute some bash script upon keyboard interrupt but it seems my python code is exiting without executing the bash script at keyboard interrupt.here is my sample code.

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
    This is strange. I do not have this problem at all. Neither with Python 2 or 3. Is it a permissions issue? – Sari May 05 '17 at 06:33

1 Answers1

0

Upon thinking about this, I think your app might be capturing the KeyboardInterrupt and preventing the encapsulating script from ever getting the exception, by forcibly killing the process or something similar. A minimal example that I could cook up which reproduces your issue is:

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"')
Sari
  • 596
  • 7
  • 12
  • the example you have given @Evey it's executing the bash script upon exit but it's only printing the message inside echo , but not starting the apache2 service though it's showing the message of service starting – Partha Sarathi Das May 05 '17 at 14:23