How to handle OS signal in a python program?

梦想的初衷 提交于 2019-12-11 00:33:17

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/33234055/how-to-handle-os-signal-in-a-python-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!