I wanted to collect some data from the Raspberry Pi I'm using to run weewx, so I decided to tackle writing an extension and adding a couple of fields to the database. More on that in another thread
I was interested in collecting CPU load and percentage (MCU?). I figured I could just call "top" and parse the results, not very difficult in Python. Most people doing this use (100 - idle) for CPU percent. I ran into something interesting though - every time I ran my test program I got the same numbers. Idle was always 31.2. This was a bit of a puzzle until it dawned on me that the processing necessary to set up the command must be putting a fixed load on the system. So how do you get around that? The solution is to run "top" for 2 iterations, with a small delay, then parse the results from the second pass. I don't know if this is common knowledge, but it sure felt like a bulb lighting up when I figured it out, so I thought I'd post it here.
The code looks like this:
try:
cmd = "top -bn2d.5" # two samples 1/2 second apart
p = Popen(cmd, shell=True, stdout=PIPE)
o = p.communicate()[0].split()
i = 1+o[1:].index('top') # find second page
o = o[i:] # delete first page
cpu_load = float(o[o.index('average:')+1].rstrip(',')) # find & extract load1
cpu_user = float(o[o.index('us,')-1]) # cpu usage in User
cpu_sys = float(o[o.index('sy,')-1]) # cpu usage in System
cpu_idle = float(o[o.index('id,')-1]) # cpu Idle
cpu_percent = 100 - cpu_idle
except (IOError, KeyError):
cpu_load = 0.0
cpu_percent = 0.0
William