在Python中,我通过Popen()
启动了一个新进程,这很好用。 现在在子进程中,我想找到父进程的进程ID。
有什么最好的方法来实现这一点,也许我可以通过Popen
构造函数传递PID,但如何传递? 或者有更好的方法吗?
PS:如果可能,我希望使用仅标准库的解决方案。
os.getppid()
方法来实现:
os.getppid()
Return the parent’s process id.
注意:这仅适用于Unix,而不是Windows。在Windows上,您可以在父进程中使用os.getpid()
,并将pid作为参数传递给使用Popen
启动的进程。os.getppid
在Windows上的支持。使用 psutil
(这里)
import psutil, os
psutil.Process(os.getpid()).ppid()
适用于Unix和Windows(即使在此平台上不存在os.getppid()
)
如果您不想使用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")
psutil.Process().ppid()
。 - user202729