Skip to main content

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))
  • 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 on SIGINT:
    @pyterminate.register(keyboard_interrupt_on_sigint=True)

    • You may want to throw a KeyboardInterrupt if there is additional exception handling defined.
  • 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

pyterminate-0.0.2.tar.gz (4.4 kB view hashes)

Uploaded Source

Built Distribution

pyterminate-0.0.2-py3-none-any.whl (4.7 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page