I would like to use the cpu_times()
method of a psutil.Popen
object to find the cumulative values after it has finished. I first tried the following:
p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
p.wait()
cpuTimes = p.cpu_times()
However, this results in a NoSuchProcess
exception because wait()
doesn't return until the process is terminated. I next tried putting the call to cpu_times()
before the call to wait()
:
p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
cpuTimes = p.cpu_times()
p.wait()
However, this yields a response of all zeros. I presume this is because it gets called immediately after the process starts. So, I added a call to time.sleep()
that would just outlast the process:
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()
This actually yields the expected value of 45 seconds (3 CPUs at 100% utilization for 15 seconds).
For a general process, however, I will not know how long it will take to finish. I would like to avoid adding an arbitrarily large sleep time just to make sure the process has finished before I make my query.
Is there a way to know that the process is done without calling wait()
or other such methods upon whose return the process has terminated?