CodyJHeiser
CodyJHeiser

Reputation: 77

Stopping a Process in Python

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()

Upvotes: 3

Views: 19398

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148890

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

Upvotes: 3

David Unric
David Unric

Reputation: 7719

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()

Upvotes: 0

Related Questions