Skip to content

Instantly share code, notes, and snippets.

@countrymarmot
Last active December 31, 2015 20:09
Show Gist options
  • Save countrymarmot/8038402 to your computer and use it in GitHub Desktop.
Save countrymarmot/8038402 to your computer and use it in GitHub Desktop.
function before exit python or ctr+c
#!/usr/bin/env python
# encoding: utf-8
import atexit
import signal
import time
def shutdown():
"""function when exit, exception
"""
print "in shutdown"
def breakp(signal, frame):
"""function when ctrl-c
"""
print "in break"
exit(0)
def main():
atexit.register(shutdown)
signal.signal(signal.SIGINT, breakp)
while True:
print "do something"
time.sleep(5)
raise Exception("exception happened")
if __name__ == "__main__":
main()
# 1,
# do something
# ^c (control+c)
# in break
# in shutdown
# 2,
# do something (5s later)
# Traceback ....
# Exception: ....
# in shutdown
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment