Skip to content

Instantly share code, notes, and snippets.

@jiteshk23
Last active December 15, 2018 07:57
Show Gist options
  • Save jiteshk23/3496d3dec8b5f38bf36375e99286ac52 to your computer and use it in GitHub Desktop.
Save jiteshk23/3496d3dec8b5f38bf36375e99286ac52 to your computer and use it in GitHub Desktop.
How to setup clean up functions
import atexit
import signal
import time
def only_once(f):
global called # python 2
called = False
def wrapped(*args, **kwargs):
global called # python 2
# nonlocal called # python 3
if not called:
called = True
f(*args, **kwargs)
return wrapped
@only_once
def Cleanup(*args): # *args to match signal handler function signature
print "all cleaned up!"
# normal
atexit.register(Cleanup)
# kill <pid>
signal.signal(signal.SIGTERM, Cleanup)
# Ctrl + c
signal.signal(signal.SIGINT, Cleanup)
time.sleep(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment