Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle OS signal in a python program?

Tags:

python

signals

I am writing a python program which reads from a queue through a infinite while loop. How can I handle signal sent by OS / Keyboard interrupt(CTRL+C) to break from the while loop and close active connections and files and exit the program gracefully instead of killing the process.

while True:
    read_from_file_and_do_something()
    ## Handle a signal of shutdown here.
    ## Send email before exiting.

This program will run as a daemon. Thus would require a signal to be sent.

like image 803
Siddharth Gupta Avatar asked Mar 10 '26 01:03

Siddharth Gupta


1 Answers

I think signal module is what you are looking for,

def handler(signum, frame):
    print 'Signal handler called with signal', signum

signal.signal(signal.SIGABRT, handler)
like image 137
nagato Avatar answered Mar 12 '26 14:03

nagato