Sending Signals to Lager Python Processes

When running a python program on your gateway via lager python, signals will automatically be propagated to the python process on the gateway. There are two ways to do this: directly sending a KeyboardInterrupt with Ctrl+C, or sending a named signal via lager python --kill --signal <Signal Name>, which corresponds to the Unix kill command used for sending signals to processes.

For an example of sending a KeyboardInterrupt save the following simple program as [keyboard.py](http://keyboard.py) and run lager python keyboard.py. After it launches it will start printing sleeping once per second.

#keyboard.py - Keyboard interrupt example
import time
try:
while True:
        print("sleeping")
        time.sleep(1)
except KeyboardInterrupt:
print("shutting down!")

Then, press Ctrl+C once to send an interrupt to the lager python process. Our code will catch the generated exception and print shutting down!

~  lager python keyboard.py
sleeping
sleeping
sleeping
^C Attempting to stop Lager Python job
shutting down!
~

For an example of sending and handling other types of exceptions, save the following program as signals.py

#signals.py - Keyboard interrupt example
import signal, time

class SIGUSR1Exception(Exception):
    pass

def handler(signum, frame):
    raise SIGUSR1Exception

def main():
    signal.signal(signal.SIGUSR1, handler)
    try:
        while True:
            print('sleeping')
            time.sleep(1)
    except SIGUSR1Exception:
        print('Got SIGUSR1, shutting down')

if __name__ == '__main__':
    main()

Then run it with: lager python signals.py. As before, it will print sleeping once per second. This time we are going to send SIGUSR1 to the python process. In a separate terminal window, run: lager python --kill --signal SIGUSR1

You will see the following output:

~ lager python signals.py
sleeping
sleeping
sleeping
sleeping
Got SIGUSR1, shutting down
~

You can see the list of available signals with lager python --help