Python - subprocess.Popen (). pid returns the pid of the parent script

I am trying to run a Python script from another Python script and get it pidso that it can be killed later.

I tried subprocess.Popen()with the argument shell=True', but thepid attribute returns thepid` of the parent script, so when I try to kill the subprocess, it kills the parent.

Here is my code:

proc = subprocess.Popen(" python ./script.py", shell=True)
pid_ = proc.pid
.
.
.
# later in my code

os.system('kill -9 %s'%pid_)

#IT KILLS THE PARENT :(
+4
source share
2 answers

shell=Truestarts a new shell process. proc.pidis the pid of this shell process. kill -9kills the shell process, turning the grandson python process into orphans.

python script , python, = True:

#!/usr/bin/env python
import os
import signal
import subprocess

proc = subprocess.Popen("python script.py", shell=True, preexec_fn=os.setsid) 
# ...
os.killpg(proc.pid, signal.SIGTERM)

script.py , @icktoofay: shell=True, proc.terminate() proc.kill() - :

#!/usr/bin/env python
import subprocess

proc = subprocess.Popen(["python", "script.py"]) 
# ...
proc.terminate()

script ; get_script_dir() .

python , (, multiprocessing) , script. , get_script_dir() multiprocessing .

+6

:

proc = subprocess.Popen(['python', './script.py'])

, hardcoded 'python' sys.executable. , proc.kill(), , PID ; , PID, os.kill, , .

+1

All Articles