av4625
Posts: 62
Joined: Sat Apr 01, 2017 11:06 am

Stopping script gracefully and turning off led's

Thu Dec 07, 2017 6:33 pm

Hi, I have code very similar to the code for the pi xmas tree.
https://thepihut.com/products/3d-xmas-t ... spberry-pi

I want to start the script remotely from python doing `python3 script.py &` in subprocess
Then I want to somehow stop the script.

What is the best way to either get the pid of the running script (baring in mind more than one python3 process is running) and killing it from python.

When it gets 'killed' I want to catch this and turn the led's off.

I wasn't sure where to put this question, any help will be greatly appreciated!

Aaron

HankB
Posts: 100
Joined: Fri Jan 01, 2016 2:45 pm

Re: Stopping script gracefully and turning off led's

Thu Dec 07, 2017 6:43 pm

(Probably belongs in a programming section.)

How do you plan to initiate stopping the script? I have a project that I want to interact with and which runs stand alone. I use a pushbutton on a GPIO pin to signal what I want. The Python script can monitor that and take action when the button is pressed. You can see the code at https://github.com/HankB/pi-video-player.

HTH

NotRequired
Posts: 190
Joined: Sat Apr 29, 2017 10:36 am
Location: Denmark

Re: Stopping script gracefully and turning off led's

Thu Dec 07, 2017 6:48 pm

You could try an exit handler: https://docs.python.org/3/library/atexit.html
Please do not ask questions in private messages, they will not help others.

User avatar
DougieLawson
Posts: 35161
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Stopping script gracefully and turning off led's

Thu Dec 07, 2017 6:54 pm

Code: Select all

from gpiozero import LEDBoard
from gpiozero.tools import random_values
from signal import pause
tree = LEDBoard(*range(2,28),pwm=True)
for led in tree:
 led.source_delay = 0.1
 led.source = random_values()
pause()
If we wrap that for led loop in a try: except: finally; block we can control what happens when you shoot the program dead with a [CTRL]+[C] or a kill -term $(pidof mytree.py) command.

Code: Select all

from gpiozero import LEDBoard
from gpiozero.tools import random_values
from signal import pause
tree = LEDBoard(*range(2,28),pwm=True)
try:
  for led in tree:
   led.source_delay = 0.1
   led.source = random_values()
  pause()
except:
  for led in tree:
    led.off()
finally:
  print ("Done and dusted")    
Note: Having anything remotely humorous in your signature is completely banned on this forum.

Any DMs sent on Twitter will be answered next month.

This is a hippy & doctor free zone.

av4625
Posts: 62
Joined: Sat Apr 01, 2017 11:06 am

Re: Stopping script gracefully and turning off led's

Sun Dec 10, 2017 9:11 pm

Thanks for the ideas. Ill give them ago!

Return to “General discussion”