How to get current CPU and RAM usage in Python?

前端 未结 16 1481
攒了一身酷
攒了一身酷 2020-11-22 04:09

What\'s your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for *nix and Windows platforms.

There s

16条回答
  •  清酒与你
    2020-11-22 05:05

    Based on the cpu usage code by @Hrabal, this is what I use:

    from subprocess import Popen, PIPE
    
    def get_cpu_usage():
        ''' Get CPU usage on Linux by reading /proc/stat '''
    
        sub = Popen(('grep', 'cpu', '/proc/stat'), stdout=PIPE, stderr=PIPE)
        top_vals = [int(val) for val in sub.communicate()[0].split('\n')[0].split[1:5]]
    
        return (top_vals[0] + top_vals[2]) * 100. /(top_vals[0] + top_vals[2] + top_vals[3])
    

提交回复
热议问题