I have a Python script which runs as a service. I have specified KillSignal=SIGINT in the .service file, so that KeyboardInterrupt is called when stopping the service, which executes some cleanup code. Everything worked fine until I added a few os.system() calls in the KeyboardInterrupt. This causes the service to no longer stop (until it times out : "stop-sigterm timed out. Killing.") I tried using subprocess.run() instead, to no avail. No problem when running this code in a terminal instead of as a service. Any suggestions on how to solve this?
(This code is running on an embedded Linux system - I need to turn off an LED to indicate the service is not running)
try:
while True:
...
except KeyboardInterrupt:
...
os.system('/usr/local/bin/set_led 2 OFF')
Make sure to re-raise the error after you've done your cleanup work, like so:
If you don't re-raise the error, it's simply gone. Your program no longer knows that it occurred. By re-raising, it will exit as usual after doing the work in the
exceptblock.