If I am running a python program on linux terminal and i abort it manually by pressing ctrl+c, how can i make my program do something when this event occurs.
something like:
if sys.exit():
print "you chose to end the program"
If I am running a python program on linux terminal and i abort it manually by pressing ctrl+c, how can i make my program do something when this event occurs.
something like:
if sys.exit():
print "you chose to end the program"
You can write a signal handling function
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
pressing Ctrl+c sends a SIGINT interrupt which would output:
you chose to end the program
Well, you can use KeyBoardInterrupt
, using a try-except block:
try:
# some code here
except KeyboardInterrupt:
print "You exited
Try the following in your command line:
import time
try:
while True:
time.sleep(1)
print "Hello"
except KeyboardInterrupt:
print "No more Hellos"
Check the KeyboardInterrupt exception in Python.
You can put your code in a try
block, catch the KeyboardInterrupt
exception with except
and let the user know that he has exited.