I am trying to get the cpu utilization of my Raspberry Pi through a Python program.
The following bash statement works great:
top -n1 | grep %Cpu
%Cpu(s): 35.6 us, 15.6 sy, 0.0 ni, 47.3 id, 0.1 wa, 0.0 hi, 1.4 si, 0.0 st
However, when I try to cut the piece of information I need in my Python program, something weird happens. The left delimiter works great, however the right one makes my result disappear (only blanks are returned)
def get_cpu_utilization():
statement = "top -n1 | grep %Cpu"
result = check_output(statement, shell=True)
# result = result[8:] this works!
# result = result[:14] doesn't work!
#The statement below doesn't work either
result = result[8:14]
print(result)
Again all I get are blanks...
What am I doing wrong here?
EDITED 1:
Running the code on my Mac works fine:
Python 2.7.10 (v2.7.10:15c95b7d81dc, May 23 2015, 09:33:12)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> result = "%Cpu(s): 39.3 us, 15.8 sy, 0.0 ni, 43.4 id, 0.1 wa, 0.0 hi, 1.3 si, 0.0 st"
>>> print(result[8:14])
39.3
>>>
EDITED 2:
A step by step for you to see what happens:
from subprocess import check_output
def get_cpu_utilization():
statement = "top -n1 | grep %Cpu"
result = check_output(statement, shell=True)
print(result)
result = result[8:]
print(result)
result = result[:6]
print(result)
result = result.strip()
print repr(result)
return result
This is what I get:
me@rpi $ sudo python cpu.py
%Cpu(s): 30.8 us, 15.2 sy, 0.0 ni, 52.6 id, 0.1 wa, 0.0 hi, 1.3 si, 0.0 st
30.8 us, 15.2 sy, 0.0 ni, 52.6 id, 0.1 wa, 0.0 hi, 1.3 si, 0.0 st
me@rpi $
result[8:14] == 35.6.resultobject before cutting it?topmay use ansi escape codes to format it's output unless you use the-b(batch) flat, so you may want to do so. This escape sequences don't show up when printed directly to the terminal, like Martijn said, userepr()to check.