我正试图通过Python程序获得树莓派的cpu利用率。
下面的bash语句非常有效:
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
然而,当我试图在我的Python程序中剪切我需要的信息时,发生了一些奇怪的事情。左边的分隔符效果很好,但是右边的分隔符会使我的结果消失(只返回空格)
def get_cpu_utilization():
statement = "top -n1 | grep %Cpu"
result = check_output(statement, shell=True)
result = result[8:14]
print(result)
再一次,我得到的都是空白。。。
我在这里做错了什么?
编辑1:
在我的Mac上运行代码很好:
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
>>>
编辑2:
一步步让您了解发生了什么:
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
这就是我得到的:
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 $