获得子进程的PID
我使用Python的多处理模块,以产生新的进程获得子进程的PID
如下:
import multiprocessing
import os
d = multiprocessing.Process(target=os.system,args=('iostat 2 > a.txt',))
d.start()
我想获得iostat命令或使用执行命令的PID多处理 模块
当我执行时:
d.pid
它给了我这个命令运行的子shell的pid。
任何帮助将是有价值的。
在此先感谢
我想你可能是出于运气的多进程模块,因为你是真正的直接分叉蟒蛇,并给予这一进程的对象,而不是过程中,你是在过程的底部兴趣树。
获得该pid的另一种方式(但可能不是最佳方式)是使用psutil模块使用从Process对象获取的pid进行查找。然而,Psutil依赖于系统,需要在每个目标平台上单独安装。
注:我不是目前正处在一个机器,我通常在工作,所以我无法提供工作代码,也不玩找到一个更好的选择,但编辑这个答案时,我可以展示你怎么可能能够做到这一点。
为了您的例子中,你可以使用subprocess
包。缺省情况下它无壳执行该命令(如os.system()
),并提供一个PID:
from subprocess import Popen
p = Popen('iostat 2 > a.txt', shell=True)
processId = p.pid
p.communicate() # to wait until the end
的Popen
还提供连接到标准输入和过程输出的能力。
注意:使用前shell=True
知道的security considerations的。
既然你似乎是使用Unix中,你可以使用一个快速ps
命令来获取子进程的细节,像我一样在这里(这是Linux特有):
import subprocess, os, signal
def kill_child_processes(parent_pid, sig=signal.SIGTERM):
ps_command = subprocess.Popen("ps -o pid --ppid %d --noheaders" % parent_pid, shell=True, stdout=subprocess.PIPE)
ps_output = ps_command.stdout.read()
retcode = ps_command.wait()
assert retcode == 0, "ps command returned %d" % retcode
for pid_str in ps_output.split("\n")[:-1]:
os.kill(int(pid_str), sig)
在Mac上:'ps -o pid,ppid -ax | grep
加耶,是的,我的答案可能是Linux特有的。 – rakslice 2011-11-22 06:23:46
要获得所有孩子递归,您可以改用: 'subprocess.Popen( 'pstree -p%d |的perl -ne \' 打印 “$ 1”,而/ \((\ d +)\)/ G \ '' % parent_pid,壳=真,标准输出= subprocess.PIPE)' – 2014-06-26 03:48:29
类似@ rakslice,您可以使用psutil:
import signal, psutil
def kill_child_processes(parent_pid, sig=signal.SIGTERM):
try:
parent = psutil.Process(parent_pid)
except psutil.NoSuchProcess:
return
children = parent.children(recursive=True)
for process in children:
process.send_signal(sig)
如果你想使用subprocess.Popen没有外壳选项,你不能给它一个shell命令(如这里显示的单串多个参数和重定向)。 – rakslice 2011-06-16 22:41:19