2

I am running a program that I would like to have stopped when a certain button is pushed.

I was thinking of running the process in the background so that the button can be pressed any time during the process and it would stop it.

I read stuff on subprocess from the documentation, but me being a beginner I have no idea how to use it, any help is appreciated.

def put(command):
        os.system(command)

        if direct == "":
            time.sleep(.5)
            arg1 = put("sudo ffmpeg -i \"" + q3 + "\" -f s16le -ar 22.05k -ac 1 - | sudo ./pifm - " + str(freq)) 
            subprocess.Popen(arg1)
            while True:
                if RPIO.input(25) == GPIO.LOW: #if button is pushed, kill process (arg1)
                    Popen.terminate()
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
CodyJHeiser
  • 67
  • 2
  • 2
  • 9
  • Are you trying to have a python program kill other processes, or have it kill itself? – aruisdante Jun 21 '14 at 21:30
  • possible duplicate of [Kill process by name in python](http://stackoverflow.com/questions/2940858/kill-process-by-name-in-python) – aruisdante Jun 21 '14 at 21:31
  • @aruisdante I am trying to kill the arg1 command that runs, it takes a while to run it, and I want to be able to stop it when I press the button. Thanks for the replies! – CodyJHeiser Jun 21 '14 at 21:34

2 Answers2

2

If you want to keep control on your subprocess, you'd better use the subprocess module. If you create it via Popen, you will be able to stop it via the kill() or terminate() methods.

Example

import subprocess
# ...
sub = subprocess.Popen(command)
# ...
sub.kill()

And you are sure you are killing your own child, even if there are numerous command running simutaneously

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

You'd need to call terminate on instance od Popen:

if direct == "":
    time.sleep(.5)
    arg1 = put("sudo ffmpeg -i \"" + q3 + "\" -f s16le -ar 22.05k -ac 1 - | sudo ./pifm - " + str(freq)) 
    myproc = subprocess.Popen(arg1)
    while True:
        if RPIO.input(25) == GPIO.LOW: #if button is pushed, kill process (arg1)
            myproc.terminate()
David Unric
  • 7,421
  • 1
  • 37
  • 65