I would like to track the current system-wide CPU usage on a Mac using Python.
I wrote code starting with "ps" and adds all the values from the "% cpu" column.
def psColumn(colName):
"""Get a column of ps output as a list"""
ps = subprocess.Popen(["ps", "-A", "-o", colName], stdout=subprocess.PIPE)
(stdout, stderr) = ps.communicate()
column = stdout.split("\n")[1:]
column = [token.strip() for token in column if token != '']
return column
def read(self):
values = map(float, psColumn("%cpu"))
return sum(values)
However, I always get high readings from 50% to 80%, probably caused by the measurement program itself. This peak CPU usage is not recorded in my Meters or other system monitoring programs. How can I get readings that are more like displaying MenuMeters? (I want to detect critical situations in which some program is chasing the processor.)
ps I tried psutil but
psutil.cpu_percent()
always returns 100%, so this is useless to me or I use it incorrectly.