python - subprocess.Popen().pid return the pid of the parent script

后端 未结 2 1006
刺人心
刺人心 2020-12-31 20:25

I am trying to run a Python script from another Python script, and getting its pid so I can kill it later.

I tried subprocess.Popen() with

2条回答
  •  攒了一身酷
    2020-12-31 21:05

    shell=True starts a new shell process. proc.pid is the pid of that shell process. kill -9 kills the shell process making the grandchild python process into an orphan.

    If the grandchild python script can spawn its own child processes and you want to kill the whole process tree then see How to terminate a python subprocess launched with shell=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)
    

    If script.py does not spawn any processes then use @icktoofay suggestion: drop shell=True, use a list argument, and call proc.terminate() or proc.kill() -- the latter always works eventually:

    #!/usr/bin/env python
    import subprocess
    
    proc = subprocess.Popen(["python", "script.py"]) 
    # ...
    proc.terminate()
    

    If you want to run your parent script from a different directory; you might need get_script_dir() function.

    Consider importing the python module and running its functions, using its object (perhaps via multiprocessing) instead of running it as a script. Here's code example that demonstrates get_script_dir() and multiprocessing usage.

提交回复
热议问题