How to get current CPU and RAM usage in Python?

前端 未结 16 1519
攒了一身酷
攒了一身酷 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 04:55

    you can read /proc/meminfo to get used memory

    file1 = open('/proc/meminfo', 'r') 
    
    for line in file1: 
        if 'MemTotal' in line: 
            x = line.split()
            memTotal = int(x[1])
            
        if 'Buffers' in line: 
            x = line.split()
            buffers = int(x[1])
            
        if 'Cached' in line and 'SwapCached' not in line: 
            x = line.split()
            cached = int(x[1])
        
        if 'MemFree' in line: 
            x = line.split()
            memFree = int(x[1])
    
    file1.close()
    
    percentage_used = int ( ( memTotal - (buffers + cached + memFree) ) / memTotal * 100 )
    print(percentage_used)
    

提交回复
热议问题