V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Hakmor
V2EX  ›  问与答

Python2 得到 CPU 和内存信息要怎么实现呢?

  •  
  •   Hakmor · 2015-08-31 17:49:36 +08:00 · 2126 次点击
    这是一个创建于 3373 天前的主题,其中的信息可能已经有所发展或是发生改变。
    3 条回复    2015-08-31 20:32:52 +08:00
    askfermi
        1
    askfermi  
       2015-08-31 17:57:04 +08:00
    ls ('cat >/proc/cpuinfo')
    ls ('cat >/proc/meminfo')
    maemual
        2
    maemual  
       2015-08-31 17:58:08 +08:00
    。。。。这个 Google 一下不就有了么。。
    psutil
    Hakmor
        3
    Hakmor  
    OP
       2015-08-31 20:32:52 +08:00
    @askfermi
    @maemual

    谢谢。附上写好的代码。

    ```python
    #!/usr/bin/env python
    import time
    import psutil

    line_num = 1

    def print_line (str ):
    print str

    #function of Get CPU State
    def getCPUstate (interval=1 ):
    return (" CPU: " + str (psutil.cpu_percent (interval )) + "%")

    #function of Get Memory
    def getMemorystate ():
    phymem = psutil.phymem_usage ()
    buffers = getattr (psutil, 'phymem_buffers', lambda: 0 )()
    cached = getattr (psutil, 'cached_phymem', lambda: 0 )()
    used = phymem.total - (phymem.free + buffers + cached )
    line = " Memory: %6s" % (
    str (int (used / 1024 / 1024 )) + "M",
    )
    return line

    def poll (interval ):
    """Retrieve raw stats within an interval window."""
    # sleep some time
    time.sleep (interval )
    # get cpu state
    cpu_state = getCPUstate (interval )
    # get memory
    memory_state = getMemorystate ()
    return (cpu_state,memory_state )

    def refresh_window (cpu_state,memory_state ):
    #print current time #cpu state #memory
    print_line (time.asctime ())
    print_line (cpu_state )
    print_line (memory_state )

    try:
    interval =0
    while 1:
    args = poll (interval )
    refresh_window (*args )
    interval = 1
    except (KeyboardInterrupt, SystemExit ):
    pass
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   916 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 22:34 · PVG 06:34 · LAX 14:34 · JFK 17:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.