【发布时间】:2014-06-25 16:37:26
【问题描述】:
在 Python 中,我通过 Popen() 启动了一个新进程,该进程运行良好。现在在子进程中我想找到父进程的ID。
实现这一点的最佳方法是什么,也许我可以通过 Popen 构造函数传递 PID,但是如何?或者有更好的方法吗?
PS:如果可能的话,我更喜欢只使用标准库的解决方案。
【问题讨论】:
在 Python 中,我通过 Popen() 启动了一个新进程,该进程运行良好。现在在子进程中我想找到父进程的ID。
实现这一点的最佳方法是什么,也许我可以通过 Popen 构造函数传递 PID,但是如何?或者有更好的方法吗?
PS:如果可能的话,我更喜欢只使用标准库的解决方案。
【问题讨论】:
如果您不想使用 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")
【讨论】:
你可以使用os.getppid():
os.getppid()Return the parent’s process id.
注意:这仅适用于 Unix,不适用于 Windows。在 Windows 上,您可以在父进程中使用 os.getpid(),并将 pid 作为参数传递给以 Popen 开头的进程。
在 Python 3.2 中添加了对 os.getppid 的 Windows 支持。
【讨论】:
使用psutil (here)
import psutil, os
psutil.Process(os.getpid()).ppid()
适用于 Unix 和 Windows(即使 os.getppid() 在此平台上不存在)
【讨论】:
ppid()是Process的成员方法,不是变量,所以上面需要改成包含括号。
【讨论】: