Search code examples
pythonterminalsubprocessterminate

Python: terminate subprocess without having access to subprocess.Popen object?


I have a script whereby I simply call a subprocess in Python using the subprocess module, like so:

import subprocess
process = subprocess.Popen(['python3', 'some_Python_script.py']

I want to be able to terminate/kill this process. However, after creating my process, in my app I lose access to the process object, and thus am not able to commonly terminate it as described in here, using process.kill.

However, is there a way to "store" some unique ID of the process, and with it be able to manipulate/terminate it later on (if it is still running)?

For ex., I am thinking of something like

process = subprocess.Popen(['python3', 'some_Python_script.py']
process_ID_string = process.id
...
...
*later on*
subprocess.kill(process_id = process_ID_string)

Is something like this possible with the subprocess module?


Solution

  • import subprocess, os, signal
    
    process = subprocess.Popen(['python3', 'some_Python_script.py']
    processId = process.pid
    
    # later on
    os.kill(processId, signal.SIGTERM)