1

I am working on Python 2.7 on windows.

How to close the program by keyboard interrupt in python.

I made some code but it asks me every time to give a input and then perform something according to that. I want that the code should not ask me every time and at any random time when I give the input it should perform the corresponding action (for my case close the program)

while 1:
var = raw_input("enter a to stop:  ")
     if var == 'a':
       break

exit()   
user3805148
  • 37
  • 1
  • 1
  • 5

3 Answers3

3

If you do not want to use the try-except construction, use can use the module signal to catch the SIGINT. The following code is from this page, where you can find a longer explanation:

import signal

def keyboardInterruptHandler(signal, frame):
    print("KeyboardInterrupt (ID: {}) has been caught. Cleaning up...".format(signal))
    exit(0)

signal.signal(signal.SIGINT, keyboardInterruptHandler)

while True:
    pass

Ỳou can also check the answers to this question

Ramon Crehuet
  • 3,679
  • 1
  • 22
  • 37
1

You can put your code in a try except block and catch keyboardInterrupt

#!/usr/bin/python
import sys
try:
     # Do something here and when you key board interrupt 
     # The except block will capture the keyboard interrupt and exit

except KeyboardInterrupt:
    sys.exit()
Ram
  • 1,115
  • 8
  • 20
-1

Try this.

try:
   while 1:
    var = raw_input("enter a to stop:  ")
    if var == 'a':
       break
except (KeyboardInterrupt, SystemExit):
    print 'program stopped manually'
    raise
except:
    # report error and proceed, 
d-coder
  • 12,813
  • 4
  • 26
  • 36