Search code examples
pythonlinuxshellraspberry-pigpio

Call a shell script on a button press & kill it after pressed again


I can't seem to figure out how to kill a script in python after it's called. Any ideas?

"Party.py":

#!/usr/bin/python
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.IN, pull_up_down=GPIO.PUD_UP)
input = GPIO.input(11)
import time
import os
#initialise a previous input variable
prev_input = 1
party = 0
while True:
  #take a reading
  input = GPIO.input(11)
  #if the last reading was low and this one high, print
  if ((not prev_input) and input):
    if (party ==  0):
        os.system("./home/tim/bin/dalitest")
        party = 1
    elif (party == 1):
        #Kill the script
        party = 0
    time.sleep(2)
  #update previous input
  prev_input = input
  #slight pause to debounce
  time.sleep(0.05)

A different python script is called here os.system("./home/tim/bin/dalitest") How do I kill the other Python script within the main one?


Solution

  • Something like this should do the trick:

    Spawning

    #spawn by path + return immediately  and get pid
    pid = os.spawnl(os.P_NOWAIT, "./home/tim/bin/dalitest")
    

    Killing

    #kill pid
    os.kill(pid, signal.SIGTERM)
    
    #wait for pid to release it back to the system
    #this will block until the child is dead
    os.waitpid(pid,0)