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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Coolio2654
  • 1,589
  • 3
  • 21
  • 46
  • If you can store the PID, why can't you store a reference to the object the same way? – Charles Duffy Mar 10 '19 at 19:27
  • (and to be clear, it's `process.pid`, as documented at https://docs.python.org/3/library/subprocess.html#subprocess.Popen.pid) – Charles Duffy Mar 10 '19 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. – Coolio2654 Mar 11 '19 at 22:39

1 Answers1

2
import subprocess, os, signal

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

# later on
os.kill(processId, signal.SIGTERM)
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 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. – Coolio2654 Mar 11 '19 at 22:39