To gracefully handle the SIGTERM signal in Python, follow these steps:
Begin by importing the required modules:
import signal
import sys
Define a signal handler function that will be invoked upon receiving the SIGTERM signal:
def sigterm_handler(signal, frame):
# Add code here to perform cleanup or any necessary operations for graceful shutdown
# ...
# Terminate the program gracefully
sys.exit(0)
Register the signal handler function to handle the SIGTERM signal:
signal.signal(signal.SIGTERM, sigterm_handler)
Proceed with your main program logic:
def main():
# Insert your main program logic here
# ...
# Keep the program running
while True:
# Your code goes here
pass
if __name__ == "__main__":
main()
Upon receiving a SIGTERM signal (e.g., by executing kill -SIGTERM <pid> in the terminal, where <pid> represents the process ID of your program), the sigterm_handler function will be triggered. Within this function, you can include any necessary cleanup tasks or actions required for a graceful shutdown, such as saving data, closing connections, or releasing resources. Finally, using sys.exit(0) ensures that the program terminates gracefully with an exit status of 0.
By implementing this approach, your Python program will be equipped to handle SIGTERM signals effectively, allowing for proper cleanup and a smooth shutdown process.