Skip to main content
 首页 » 编程设计

python之如何在 psutil.Popen 完成后但在终止之前获取进程运行的 cpu_times

2024年11月24日13mq0036

我想使用psutil.Popen 对象的cpu_times() 方法来完成 后查找累积值。我首先尝试了以下方法:

p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True) 
p.wait() 
cpuTimes = p.cpu_times() 

但是,这会导致 NoSuchProcess 异常,因为 wait() 在进程终止之前不会返回。接下来,我尝试将对 cpu_times() 的调用 放在对 wait() 的调用之前:

p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True) 
cpuTimes = p.cpu_times() 
p.wait() 

但是,这会产生全零响应。我认为这是因为它在进程启动后立即被调用。因此,我添加了对 time.sleep() 的调用,这将比该过程更持久:

p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True) 
time.sleep(15.) # b/c -t 15 in subprocess means it will take 15 seconds 
cpuTimes = p.cpu_times() 
p.wait() 

这实际上产生了 45 秒的预期值(3 个 CPU 以 100% 使用率持续 15 秒)。

但是,对于一般流程,我不知道需要多长时间才能完成。我想避免添加任意长的休眠时间,只是为了确保在我进行查询之前该过程已完成。

有没有一种方法可以在不调用 wait() 或其他返回过程终止的类似方法的情况下知道该过程已完成?

请您参考如下方法:

好的,我找到了解决方案。它实际上非常简单,所以我可能应该在发布我的问题之前考虑它,但我想这就是这些事情有时的发展方式。

p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True) 
cpuTimes = p.cpu_times() 
while True: 
    time.sleep(1e-4) 
    cpuTimes = p.cpu_times()  # Make sure to do this before the call to poll() 
    retCode = p.poll() 
    if retCode is not None: 
        break 

在这里,我在启动包含调用的子进程后添加了一个循环 进程的 cpu_times() 和 poll() 方法。

poll() 方法是一种检查子进程是否完成的非阻塞方式。通过在调用 poll() 之前调用 cpu_times(),耗时极少,因此我们可以考虑最后一个调用 cpu_times() 以产生准确的结果。

请注意,如果进程已完成,在 poll() 之后调用 cpu_times() 时会出现异常。这是在调用 poll() 之前调用 cpu_times() 的另一个原因。

sleep() 方法的参数不是特别重要,但会影响子进程完成后和循环终止前耗时。如果子进程永远不会完成,您可能还可以添加某种慷慨的超时来防止无限循环。