获取子进程的pid

2024-10-02 12:34:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python的多处理模块生成新的进程

具体如下:

import multiprocessing
import os
d = multiprocessing.Process(target=os.system,args=('iostat 2 > a.txt',))
d.start()

我想获得iostat命令的pid或使用多处理执行的命令 模块

当我执行时:

 d.pid 

它给了我运行这个命令的子shell的pid。

任何帮助都是有价值的。

提前谢谢


Tags: 模块import命令txttarget进程osargs
3条回答

因为您似乎在使用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)

类似于@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)

我认为对于多进程模块,您可能会走运,因为您实际上是直接派生python,并且在进程树的底部得到的是该进程对象,而不是您感兴趣的进程。

获取pid的另一种方法,但可能不是最佳方法,是使用psutil模块使用从Process对象获得的pid来查找它。但是,Psutil依赖于系统,需要在每个目标平台上分别安装。

注意:我目前不在一台我通常工作的机器上,所以我不能提供工作代码,也不能四处寻找更好的选项,但会在我可以显示您可能如何做到这一点时编辑此答案。

相关问题 更多 >

    热门问题