Stopping a Process in Python

14,311

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

Share:
14,311
CodyJHeiser
Author by

CodyJHeiser

I am a student in high school (none of my questions are homework questions by the way) and I love to learn about computers! Currently learning Python, mostly from immersion. Love technology and helping other people when I can!

Updated on June 04, 2022

Comments

  • CodyJHeiser
    CodyJHeiser almost 2 years

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