Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # The MIT License (MIT)
- # ...
- """\
- Сlean exit for Python scripts after Ctrl-C.
- Inspired by xlab’s Closer for Go (Golang).
- """
- from functools import wraps
- import signal
- import sys
- _signals = (
- signal.SIGINT,
- signal.SIGTERM,
- signal.SIGHUP
- )
- _handlers = []
- def defer(foo):
- """\
- Push `foo` to the stack...
- """
- @wraps(foo)
- def handler(*args, **kw):
- try:
- foo(*args, **kw)
- except Exception as e:
- print(e) # handle the exception here
- _handlers.append(handler)
- def close(exitcode=0):
- """\
- Call deferred functions and exit...
- """
- for handler in _handlers:
- handler()
- sys.exit(exitcode)
- def listen(*signals, override=False):
- """\
- Wait for SIGINT, SIGTERM and SIGHUP OS signals
- and call functions from stack in reverse order...
- """
- for sig in signals if override else signals + _signals:
- signal.signal(sig, close)
Advertisement
Add Comment
Please, Sign In to add comment