python 如何获取进程的祖父母ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1728330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:58:01  来源:igfitidea点击:

How to get process's grandparent id

pythonlinuxprocesssubprocess

提问by Anurag Uniyal

How can i get process id of the current process's parent?
In general given a process id how can I get its parent process id?
e.g. os.getpid() can be used to get the proccess id, and os.getppid() for the parent, how do I get grandparent,

如何获取当前进程的父进程的进程 ID?
一般来说,给定一个进程ID,我怎样才能获得它的父进程ID?
例如 os.getpid() 可用于获取进程 ID,而 os.getppid() 可用于获取父进程,我如何获取祖父母,

My target is linux(ubuntu) so platform specific answers are ok.

我的目标是 linux(ubuntu) 所以平台特定的答案是可以的。

采纳答案by pixelbeat

linux specific:

linux特定:

os.popen("ps -p %d -oppid=" % os.getppid()).read().strip()

回答by Giampaolo Rodolà

By using psutil ( https://github.com/giampaolo/psutil):

通过使用 psutil ( https://github.com/giampaolo/psutil):

>>> import psutil
>>> psutil.Process().ppid()
2335
>>> psutil.Process().parent()
<psutil.Process (pid=2335, name='bash', cmdline='bash') at 140052120886608>
>>> 

回答by paxdiablo

I don't think you can do this in a portable Python fashion. But there are two possibilities.

我认为您无法以可移植的 Python 方式执行此操作。但是有两种可能。

  1. The information is available from the pscommand so you could analyze that.
  2. If you have a system with the procfile systems, you can open the file /proc/<pid>/statusand search for the line containing PPid:, then do the same for that PID.
  1. 该信息可从ps命令中获得,因此您可以对其进行分析。
  2. 如果您的系统带有proc文件系统,则可以打开文件/proc/<pid>/status并搜索包含 的行PPid:,然后对该 PID 执行相同操作。

For example the following script will get you your PID, PPID and PPPID, permissions willing:

例如,以下脚本将为您提供您的 PID、PPID 和 PPPID,以及愿意的权限:

#!/bin/bash
pid=$$
ppid=$(grep PPid: /proc/${pid}/status | awk '{print '})
pppid=$(grep PPid: /proc/${ppid}/status | awk '{print '})
echo ${pid} ${ppid} ${pppid}
ps -f -p "${pid},${ppid},${pppid}"

produces:

产生:

3269 3160 3142
UID        PID  PPID  C STIME TTY          TIME CMD
pax       3142  2786  0 18:24 pts/1    00:00:00 bash
root      3160  3142  0 18:24 pts/1    00:00:00 bash
root      3269  3160  0 18:34 pts/1    00:00:00 /bin/bash ./getem.sh

Obviously, you'd have to open those files with Python.

显然,您必须使用 Python 打开这些文件。

回答by tzot

from __future__ import with_statement

def pnid(pid=None, N=1):
    "Get parent (if N==1), grandparent (if N==2), ... of pid (or self if not given)"
    if pid is None:
        pid= "self"

    while N > 0:
        filename= "/proc/%s/status" % pid
        with open(filename, "r") as fp:
            for line in fp:
                if line.startswith("PPid:"):
                    _, _, pid= line.rpartition("\t")
                    pid= pid.rstrip() # drop the '\n' at end
                    break
            else:
                raise RuntimeError, "can't locate PPid line in %r" % filename
        N-= 1

    return int(pid) # let it fail through


>>> pnid()
26558
>>> import os
>>> os.getppid()
26558
>>> pnid(26558)
26556
>>> pnid(N=2)
26556
>>> pnid(N=3)
1

回答by Nick Dixon

If you have a POSIX-compliant 'ps' command, which allows you to specify the columns you want, like this: ps -o pid,ppid

如果您有符合 POSIX 的“ps”命令,它允许您指定所需的列,如下所示: ps -o pid,ppid

You could then try:

然后你可以尝试:

import os
import re

ps = os.popen("ps -o pid,ppid")
ps.readline()    # discard header
lines = ps.readlines()
ps.close

procs = [ re.split("\s+", line.strip()) for line in lines ]

parent = {}
for proc in procs:
    parent[ int(proc[0]) ] = int(proc[1])

Now you can do:

现在你可以这样做:

parent[ parent[pid] ]

You could even write a function to list a process' ancestors:

您甚至可以编写一个函数来列出进程的祖先:

def listp(pid):
    print(pid)
    if parent.has_key(pid):
        listp( parent[pid] )

回答by ddaa

I do not think you can do this portably in the general case.

我不认为你可以在一般情况下轻松地做到这一点。

You need to get this information from the process list (e.g. through the pscommand), which is obtained in a system-specific way.

您需要从进程列表(例如通过ps命令)中获取此信息,该信息以特定于系统的方式获取。