Search code examples
pythonflasksubprocesskillterminate

Terminate a python program running from another program


How to use subprocess to terminate a program which is started at boot? I ran across this question and found wordsforthewise's answer and tried it but nothing happens.

Wordsforthewise' Answer:

import subprocess as sp

extProc = sp.Popen(['python','myPyScript.py']) # runs myPyScript.py 

status = sp.Popen.poll(extProc) # status should be 'None'

sp.Popen.terminate(extProc) # closes the process

status = sp.Popen.poll(extProc) # status should now be something other than 'None' ('1' in my testing)

I have a program /home/pi/Desktop/startUpPrograms/facedetection.py running at boot by a Cronjob and I want to kill it from a flask app route like this.

Assigning program name to extProc = program_name would work? If yes how to assign it?

@app.route("/killFD", methods=['GET', 'POST'])
def killFaceDetector():
    #kill code goes here.

Solution

  • Since you say the program is run by cronjob, you will have no handle to the program's PID in Python.

    You'll have to iterate over all processes to find the one(s) to kill... or more succinctly, just use the pkill utility, with the -f flag to have it look at the full command line. The following will kill all processes (if your user has the permission to do so) that have facedetection.py in the command line.

    import os
    
    os.system('pkill -f facedetection.py')