Guest User

Untitled

a guest
Aug 6th, 2015
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.97 KB | None | 0 0
  1. # The MIT License (MIT)
  2. # ...
  3.  
  4. """\
  5. Сlean exit for Python scripts after Ctrl-C.
  6. Inspired by xlab’s Closer for Go (Golang).
  7. """
  8.  
  9. from functools import wraps
  10. import signal
  11. import sys
  12.  
  13. _signals = (
  14.     signal.SIGINT,
  15.     signal.SIGTERM,
  16.     signal.SIGHUP
  17. )
  18. _handlers = []
  19.  
  20. def defer(foo):
  21.     """\
  22.    Push `foo` to the stack...
  23.    """
  24.     @wraps(foo)
  25.     def handler(*args, **kw):
  26.         try:
  27.             foo(*args, **kw)
  28.         except Exception as e:
  29.             print(e)  # handle the exception here
  30.    
  31.     _handlers.append(handler)
  32.  
  33. def close(exitcode=0):
  34.     """\
  35.    Call deferred functions and exit...
  36.    """
  37.     for handler in _handlers:
  38.         handler()
  39.     sys.exit(exitcode)
  40.  
  41. def listen(*signals, override=False):
  42.     """\
  43.    Wait for SIGINT, SIGTERM and SIGHUP OS signals
  44.    and call functions from stack in reverse order...
  45.    """
  46.     for sig in signals if override else signals + _signals:
  47.         signal.signal(sig, close)
Advertisement
Add Comment
Please, Sign In to add comment