Terminating python script and releasing resources

Python script can be used as a background running service in order to provide some functionality. This service is often stopped on very aggressive way with process termination. Therefore some resources may not be released or child threads stopped.Below are two options how to handle script termination.

1.  Catching KeyboardInterrupt and SystemExit errors:

 try:
     running_service()
 except (KeyboardInterrupt, SystemExit):
     print("Termination occurred")
     handle_termination()
     sys.exit()

http://stackoverflow.com/questions/2564137/python-how-to-terminate-a-thread-when-main-program-ends

2.  Register on system signals:

Described in this post:  How To Catch “Kill” Events with Python

Advertisements