0
0
PythonHow-ToBeginner · 3 min read

How to Gracefully Shutdown Python Program: Simple Guide

To gracefully shutdown a Python program, use the signal module to catch termination signals like SIGINT or SIGTERM. Then, run cleanup code inside the signal handler before exiting the program cleanly.
📐

Syntax

Use the signal.signal() function to register a handler for termination signals. The handler is a function that takes two arguments: the signal number and the current stack frame. Inside this handler, you can perform cleanup tasks and then exit the program.

Common signals to handle are signal.SIGINT (Ctrl+C) and signal.SIGTERM (termination request).

python
import signal
import sys

def handler(signum, frame):
    print('Signal received:', signum)
    # Cleanup code here
    sys.exit(0)

signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGTERM, handler)

# Program main loop
while True:
    pass
💻

Example

This example shows how to catch Ctrl+C (SIGINT) to stop a running program gracefully. It prints a message, cleans up, and exits without error.

python
import signal
import sys
import time

def graceful_exit(signum, frame):
    print('\nGraceful shutdown initiated...')
    # Example cleanup: close files, release resources
    print('Cleanup done. Exiting now.')
    sys.exit(0)

signal.signal(signal.SIGINT, graceful_exit)

print('Program running. Press Ctrl+C to exit.')

while True:
    time.sleep(1)
Output
Program running. Press Ctrl+C to exit. Graceful shutdown initiated... Cleanup done. Exiting now.
⚠️

Common Pitfalls

  • Not handling signals causes the program to exit abruptly without cleanup.
  • Using sys.exit() outside the signal handler may skip cleanup.
  • Ignoring signals like SIGTERM can cause issues in production environments.
  • Blocking calls without interruption support can delay shutdown.

Always ensure your cleanup code is safe and quick to avoid hanging the shutdown process.

python
import signal
import sys
import time

# Wrong: no signal handling
print('Running without signal handler. Press Ctrl+C.')
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print('Caught KeyboardInterrupt but no cleanup.')
    sys.exit(1)

# Right: with signal handler

def handler(signum, frame):
    print('Signal received, cleaning up...')
    sys.exit(0)

signal.signal(signal.SIGINT, handler)
print('Running with signal handler. Press Ctrl+C.')
while True:
    time.sleep(1)
📊

Quick Reference

Tips for graceful shutdown in Python:

  • Use signal.signal() to catch SIGINT and SIGTERM.
  • Put cleanup code inside the signal handler function.
  • Call sys.exit() after cleanup to stop the program.
  • Test shutdown by pressing Ctrl+C or sending termination signals.
  • Keep cleanup code fast and safe to avoid delays.

Key Takeaways

Use the signal module to catch termination signals for graceful shutdown.
Place cleanup code inside the signal handler to release resources properly.
Call sys.exit() after cleanup to exit the program cleanly.
Handle both SIGINT (Ctrl+C) and SIGTERM for robust shutdown.
Avoid long-running cleanup to prevent shutdown delays.