首页 > 解决方案 > 是否可以通过使用 `psutil` 或任何其他 Python 包来获取兄弟进程的 PID?

问题描述

我正在运行一组并行计算。

我正在尝试使用psutil来跟踪计算(如果有人有更好的解决方案,请告诉我)

>>> p = psutil.Process(4370)
>>> p.cpu_percent()
0.0
>>> p.cpu_times()
pcputimes(user=6440.78, system=5.4, children_user=0.0, children_system=0.0)
>>> p.cpu_affinity()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> p.cpu_num()
2 

我猜最后一个的值为 2p.cpu_num()表示这项工作是在并行计算上,还有另一个同级进程同时进行计算。

是否可以通过使用psutil或任何其他 Python 包获取兄弟进程的 PID?

标签: pythonparallel-processing

解决方案


我猜最后一个得到的值为2forp.cpu_num()表明这项工作是在并行计算上”

不,这并不意味着其他任何事情,只是进程p当前从所有可用的 CPU 映射到第二个 CPU(O/S 任务调度程序决定作业将执行哪个 CPU/核心 + 进程关联性设置可能会限制这样的选择)

>>> print( p.cpu_num.__doc__ )
Return what CPU this process is currently running on.
            The returned number should be <= psutil.cpu_count()
            and <= len(psutil.cpu_percent(percpu=True)).
            It may be used in conjunction with
            psutil.cpu_percent(percpu=True) to observe the system
            workload distributed across CPUs.

Q :是否可以通过使用获取兄弟进程的 PIDpsutil

是的。如何?遵循文档将任何满足您的需求和期望的遍历树策略组装到系统级通用流程监视器就足够了。

>>> aParentOfThisPROCESS = psutil.Process( thisProcess.parent().pid )
>>> aParentOfThisPROCESS.threads()
6
>>> aParentOfThisPROCESS.open_files()
[popenfile(path='/XXXXXXXXXXXXXXXX', fd=8, position=0, mode='r', flags=32768)]

>>> print( aParentOfThisPROCESS.children.__doc__ )
Return the children of this process as a list of Process
        instances, pre-emptively checking whether PID has been reused.
        If *recursive* is True return all the parent descendants.

        Example (A == this process):

         A ─┐
            │
            ├─ B (child) ─┐
            │             └─ X (grandchild) ─┐
            │                                └─ Y (great grandchild)
            ├─ C (child)
            └─ D (child)

        >>> import psutil
        >>> p = psutil.Process()
        >>> p.children()
        B, C, D
        >>> p.children(recursive=True)
        B, X, Y, C, D

        Note that in the example above if process X disappears
        process Y won't be listed as the reference to process A
        is lost.

推荐阅读