【问题标题】:After starting process, how to get parent's PID in the child?启动进程后,如何在子进程中获取父 PID?
【发布时间】:2014-06-25 16:37:26
【问题描述】:

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

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

PS:如果可能的话,我更喜欢只使用标准库的解决方案。

【问题讨论】:

    标签: python process


    【解决方案1】:

    如果您不想使用 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")
    

    【讨论】:

      【解决方案2】:

      你可以使用os.getppid():

      os.getppid()

      Return the parent’s process id.
      

      注意:这仅适用于 Unix,不适用于 Windows。在 Windows 上,您可以在父进程中使用 os.getpid(),并将 pid 作为参数传递给以 Popen 开头的进程。

      在 Python 3.2 中添加了对 os.getppid 的 Windows 支持。

      【讨论】:

      • @Dull Bananas 编辑其他人的答案时要小心。为什么在将其“更新”到 python3 时删除了我的答案的重要部分?您删除了有关如何在 python添加一个段落,说明何时/如何/什么发生了变化,不要删除已经存在的内容,最多指定在这些特定版本的软件中是这样的。
      【解决方案3】:

      使用psutil (here)

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

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

      【讨论】:

      • 谢谢,但如果可能的话,我更喜欢只使用 Python 标准库的解决方案。
      【解决方案4】:

      ppid()是Process的成员方法,不是变量,所以上面需要改成包含括号。

      来源:psutil documentation

      【讨论】:

        猜你喜欢
        • 2015-09-20
        • 2010-09-16
        • 2015-01-05
        • 2012-05-21
        • 2021-05-14
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 2017-10-11
        相关资源
        最近更新 更多