Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python- How to check if program gets aborted by user while running?

Tags:

python

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"
like image 209
Neha Verma Avatar asked Nov 30 '22 19:11

Neha Verma


1 Answers

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

like image 88
Ashoka Lella Avatar answered Dec 06 '22 11:12

Ashoka Lella