Kaguei Nakueka
Kaguei Nakueka

Reputation: 1108

String cutting in Python with a weird behaviour

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 $ 

Upvotes: 0

Views: 81

Answers (1)

TobiasWeis
TobiasWeis

Reputation: 492

There seem to be some special characters in between. Generally using fixed indices for this problem does not seem to be very good, because sometimes you might also have lesser digits.

I used the following method which works nicely:

statement = "top -n1 | grep %Cpu"
result = check_output(statement, shell=True).split()
print result[1] // this is the string representing the value you want
print float(result[1]) // conversion to float works, in case you want 

to compute something from it

Upvotes: 1

Related Questions