Created
January 25, 2014 07:15
-
-
Save poc7667/8612916 to your computer and use it in GitHub Desktop.
Implement signal handler in Pyhton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
http://stackoverflow.com/questions/930519/how-to-run-one-last-function-before-getting-killed-in-python | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import sys | |
reload(sys) | |
sys.setdefaultencoding('utf-8') | |
import argparse | |
import re | |
import os | |
import time | |
import string | |
import difflib | |
import pdb | |
import traceback | |
from awesome_print import ap | |
from pprint import pprint as pp | |
from timeit import default_timer as timer | |
#3rd part package | |
from lxml import etree | |
from BeautifulSoup import BeautifulSoup | |
from twisted.internet import protocol, reactor | |
from signal import * | |
#Load custom library (remember to set PYTHONPATH in your .bashrc) | |
def signal_handler(*args): | |
print "receive kill signal" | |
sys.exit(0) | |
def main(): | |
try: | |
for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM): | |
signal(sig, signal_handler) | |
myPID = os.getpid() | |
print myPID | |
while True: | |
print myPID | |
time.sleep(0.8) | |
pass | |
except KeyboardInterrupt as e: | |
print("ctrl C pressed") | |
raise e | |
except BaseException as e: | |
traceback.print_exc(file=sys.stdout) | |
raise e | |
pass | |
if __name__ == '__main__': | |
start_time = timer() | |
main() | |
print("Elapsed time : %f " % (timer()-start_time)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment