2

I have googled for code to get the CPU load on RPi3. I found this code:

import os

def getCPUuse():
    return str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip())

For me it only returns an empty string.

Where is the problem in this code?

EDIT:

I call it like this:

while True:
    time.sleep(0.2)
    use = getCPUuse()
    print(use)
monamona
  • 1,195
  • 2
  • 17
  • 43

2 Answers2

1

Take off the strip() and just do readline. That worked for me.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
starke1981
  • 26
  • 1
  • 1
    This one-liner (actually only half of the line) seems to be an actual though short attempt to answer. Thanks for your contribution. However, if you could add some explanation of how your proposed solution works and why it is supposed to help - that would make it more convincing and helpful. – Yunnosch May 29 '20 at 16:09
1

You can use the gpiozero module - it comes pre-installed with Raspberry Pi OS. So you can use this code, it is a bit easier to read too (in my opinion):

from gpiozero import LoadAverage

print(str(int(LoadAverage(minutes=1).load_average*100))+"%")

EDIT: This link may help: https://gpiozero.readthedocs.io/en/stable/api_internal.html#loadaverage

Arca Ege Cengiz
  • 315
  • 3
  • 16