I'm using GPIO in a Python script, and I've wrapped my code in a
try... except block so that GPIO is exited elegantly if I need to abort the script:
GPIO.setup(17, GPIO.OUT) # Configure GPIO so that an LED can be lit try: GPIO.output(17, True) # Switch on the LED #Do other stuff.... except: print("exiting") GPIO.output(17, False) # Switch off the LED GPIO.cleanup()
This works well - the LED is switched off if I use CTRL-C to abort the script.
Next, I start this script on reboot, via a cron job (I'm using NOOBS and it automatically boots into GUI mode). This also works well - I can see the LED light up once the script starts, and I can see the process running using
ps aux | grep...
The problem is that, since it's running in the background, I need to use
sudo kill to abort the script. This terminates the process but the LED remains lit, so presumably the script just dies instantly (rather than entering the
except block as with CTRL-C).
How can I shutdown the GPIO elegantly when using
kill to terminate a Python script which is running in the background?