代码之家  ›  专栏  ›  技术社区  ›  Kaguei Nakueka

Python中具有奇怪行为的字符串切割

  •  0
  • Kaguei Nakueka  · 技术社区  · 9 年前

    我正试图通过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:]  this works!
        # result = result[:14] doesn't work!
        #The statement below doesn't work either 
        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 $ 
    
    1 回复  |  直到 9 年前
        1
  •  1
  •   TobiasWeis    9 年前

    中间似乎有一些特殊的人物。通常,使用固定索引解决这个问题似乎不是很好,因为有时您可能也有较小的数字。

    我使用了以下方法,效果很好:

    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 
    

    从中计算一些东西