Handle graceful process termination
Project description
Safe Exit is a Python package that provides functionality to handle graceful process termination. The package allows users to register functions that will be called when the program exits.
Difference from atexit
Python has a standard module called atexit that does something similar, but atexit cannot handle cases where a program is killed by a signal not handled by Python.
Python only handles the SIGINT signal and does not handle SIGTERM, SIGQUIT, and SIGHUP signals. On Windows, programs can also be killed by SIGBREAK and CTRL_CLOSE_EVENT.
Safe Exit can handle all these signals:
On POSIX systems: SIGINT, SIGTERM, SIGQUIT, and SIGHUP
On Windows:
SIGINT, SIGTERM, SIGBREAK
CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT
Windows also has CTRL_C_EVENT and CTRL_BREAK_EVENT which Python translate to SIGINT and SIGBREAK signals, respectively. On windows, SIGTERM is implemented only for the current process, there is no way to send SIGTERM to other processes.
Installation
To install Safe Exit, simply run:
pip install safe-exit
Usage
Just register a cleanup function like you would with atexit:
import safe_exit
def cleanup_function():
# Perform cleanup tasks
safe_exit.register(cleanup_function)
The register function can also be used as a decorator:
@safe_exit.register
def cleanup_function():
# Perform cleanup tasks
Signal handling is configurable. Call the config function before registering functions. The following code configures safe_exit to handle SIGQUIT and SIGHUP signals:
from safe_exit import ConfigFlag, config, register
config(ConfigFlag.SIGQUIT | ConfigFlag.SIGHUP)
@register
def cleanup()
print("clean up")
To nicely kill a process, giving it a chance to clean up:
process_id = ...
safe_exit.safe_kill(process_pid)
Contributing
Contributions to Safe Exit are welcome! If you would like to contribute or have any ideas for improvements, please feel free to open an issue on the project’s issue tracker or get in touch with the maintainer directly.
License
Safe Exit is released under the MIT License. See the LICENSE.txt file for more details.
Project details
Release history Release notifications | RSS feed
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 safe_exit-0.1.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | fd51a192b2e4fbe5a3b9506a0c1cc7f6609abceee31780b26d0f74bb6e1e13b5 |
|
MD5 | 4e86d2aed7247fbe9f814eb81f8c5220 |
|
BLAKE2b-256 | f03b584f38b58340d40884f379776ed41e8c2f89d2492f03ed06d2318e57349b |