在启动进程后,如何在子进程中获取父进程的PID?

13

在Python中,我通过Popen()启动了一个新进程,这很好用。 现在在子进程中,我想找到父进程的进程ID。

有什么最好的方法来实现这一点,也许我可以通过Popen构造函数传递PID,但如何传递? 或者有更好的方法吗?

PS:如果可能,我希望使用仅标准库的解决方案。

4个回答

25
您可以使用 os.getppid() 方法来实现:

os.getppid()

Return the parent’s process id.
注意:这仅适用于Unix,而不是Windows。在Windows上,您可以在父进程中使用os.getpid(),并将pid作为参数传递给使用Popen启动的进程。
Python 3.2中添加了对os.getppid在Windows上的支持。

14

使用 psutil (这里)


import psutil, os
psutil.Process(os.getpid()).ppid()

适用于Unix和Windows(即使在此平台上不存在os.getppid()


1
谢谢,但如果可能的话,我更喜欢使用仅限于Python标准库的解决方案。 - Team AIGD
可以缩写为psutil.Process().ppid() - user202729

1

ppid()是Process的成员方法,不是变量,因此上述代码需要修改以包括括号。

来源:psutil文档


0

如果您不想使用psutil(例如,由于安装依赖项和IT请求所需的环境不允许),那么以下是您可以手动在Linux上进行操作的方法。

def get_parent_process_id(pid: int) -> int:
    # Read /proc/<pid>/status and look for the line `PPid:\t120517\n`
    with open(f"/proc/{pid}/status", encoding="ascii") as f:
        for line in f.readlines():
            if line.startswith("PPid:\t"):
                return int(line[6:])
    raise Exception(f"No PPid line found in /proc/{pid}/status")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接