0

On my Raspberry pi 3, I have a Python script that opens at startup in the background. In the script there is a function that acquires the percentage of CPU used.

The function is as follows:

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

If I run the program manually the function returns the value to me correctly, instead if the program is loaded at the start in the background the function does not return any value to me.

I searched everywhere, but I can't understand why.

Can someone help me?

Thanks

PS I don't want to use the psutil library!

Giammo
  • 53
  • 8
  • Maybe duplicate of https://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage-in-python – eatmeimadanish Dec 04 '19 at 16:25
  • Consider using the full path to both `top` and `awk` to start with. Not knowing how `if the program is loaded at the start in the background` is done doesn't help us in helping you ... – tink Dec 04 '19 at 17:10

1 Answers1

0

I managed to solve it alone.

I publish the solution so that it can help someone!

def getCPUuse():
    return(str(os.popen("top -b -n1 | grep 'Cpu(s)' | awk '{print $2 + $4}'").readline().strip())) 
Giammo
  • 53
  • 8