Exit programs gracefully.
Project description
pyterminate
Reliably run cleanup code upon program termination.
Table of Contents
Why does this exist?
There are currently two builtin modules for handling termination behavior
in Python: atexit
and
signal
. However, using them
directly leads to a lot of repeated boilerplate code, and some non-obvious
behaviors that can be easy to accidentally get wrong, which is why I wrote this
package.
The atexit
module is currently insufficient since it fails to handle signals.
The signal
module is currently insufficient since it fails to handle normal
or exception-caused exits.
Typical approaches would include frequently repeated code registering a
function both with atexit
and on desired signals. However, extra care
sometimes needs to be taken to ensure the function doesn't run twice (or is
idempotent), and that a previously registered signal handler gets called.
What can it do?
This packages does or allows the following behavior:
-
Register a function to be called on program termination
- Always on normal or exception-caused termination:
@pyterminate.register
- Configurable for any desired signals:
@pyterminate.register(signals=(signal.SIGINT, signal.SIGABRT))
- Always on normal or exception-caused termination:
-
Allows multiple functions to be registered
-
Will call previous registered signal handlers
-
Allows zero or non-zero exit codes on captured signals:
@pyterminate.register(successful_exit=True)
-
Allows suppressing or throwing of
KeyboardInterrupt
onSIGINT
:
@pyterminate.register(keyboard_interrupt_on_sigint=True)
- You may want to throw a
KeyboardInterrupt
if there is additional exception handling defined.
- You may want to throw a
-
Allows functions to be unregistered:
pyterminate.unregister(func)
-
Ignore multiple repeated signals to allow the registered functions to complete
- However, it can be canceled upon receipt of another signal. Desired behavior could vary application to application, but this feels appropriate for the most common known use cases.
Quickstart
python3 -m pip install pyterminate
import signal
import pyterminate
@pyterminate.register(
args=(None,),
kwargs={"b": 42},
signals=(signal.SIGINT, signal.SIGTERM),
successful_exit=True,
keyboard_interrupt_on_sigint=True
)
def cleanup(*args, **kwargs):
...
# or
pyterminate.register(cleanup, ...)
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for pyterminate-0.0.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 47be97afc71d18cbef00bd01d36d4fe2668c873a7fb2bc9771b31e313940c6a6 |
|
MD5 | c90691fb6c43b1ae1c5a0cb2c9bf9f27 |
|
BLAKE2b-256 | 2cb29159e5a71b841e9eef090ca4874f1be7f6131c20a3c20867c1f1dfb6cd54 |