1

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?

3
  • If you can store the PID, why can't you store a reference to the object the same way? Commented Mar 10, 2019 at 19:27
  • (and to be clear, it's process.pid, as documented at docs.python.org/3/library/subprocess.html#subprocess.Popen.pid) Commented Mar 10, 2019 at 19:28
  • Because I am working with Dash, and the callbacks within Dash behave like local functions in that their variables are also local, except only basic variables like strings can be returned. Commented Mar 11, 2019 at 22:39

1 Answer 1

2
import subprocess, os, signal

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

# later on
os.kill(processId, signal.SIGTERM)
Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect. I knew my intuition was on the right track ^^; , but subprocess's doc's weren't making it easy for me to find this functionality. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.