python - subprocess.Popen().pid 返回父脚本的pid

2022-01-18 00:00:00 python subprocess

问题描述

我正在尝试从另一个 Python 脚本运行一个 Python 脚本,并获取它的 pid 以便稍后我可以杀死它.

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

我用参数 shell=True' 尝试了 subprocess.Popen(),但是pid属性返回了父脚本的pid`,所以当我试图杀死子进程时,它会杀死父进程.

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

这是我的代码:

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 :(


解决方案

shell=True 启动一个新的 shell 进程.proc.pid 是那个 shell 进程的 pid.kill -9 杀死 shell 进程,使孙子 python 进程成为孤儿.

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.

如果孙子 python 脚本可以产生自己的子进程,并且您想杀死整个进程树,请参阅 如何终止 python使用 shell=True 启动的子进程:

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)

如果 script.py 没有产生任何进程,则使用 @icktoofay 建议:dropshell=True,使用列表参数,并调用 proc.terminate()proc.kill() -- 后者最终总是有效:

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()

如果你想从不同的目录运行你的父脚本;您可能需要 get_script_dir() 函数.

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

考虑导入 python 模块并运行它的函数,使用它的对象(可能通过 multiprocessing)而不是作为脚本运行它.这是 代码示例,演示了 get_script_dir()multiprocessing 用法.

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.

相关文章