How to get current CPU and RAM usage in Python?

前端 未结 16 1484
攒了一身酷
攒了一身酷 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:56

    You can use psutil or psmem with subprocess example code

    import subprocess
    cmd =   subprocess.Popen(['sudo','./ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) 
    out,error = cmd.communicate() 
    memory = out.splitlines()
    

    Reference http://techarena51.com/index.php/how-to-install-python-3-and-flask-on-linux/

    https://github.com/Leo-g/python-flask-cmd

    0 讨论(0)
  • 2020-11-22 04:58

    Only for Linux: One-liner for the RAM usage with only stdlib dependency:

    import os
    tot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:])
    

    edit: specified solution OS dependency

    0 讨论(0)
  • 2020-11-22 05:00

    I feel like these answers were written for Python 2, and in any case nobody's made mention of the standard resource package that's available for Python 3. It provides commands for obtaining the resource limits of a given process (the calling Python process by default). This isn't the same as getting the current usage of resources by the system as a whole, but it could solve some of the same problems like e.g. "I want to make sure I only use X much RAM with this script."

    0 讨论(0)
  • 2020-11-22 05:04

    We chose to use usual information source for this because we could find instantaneous fluctuations in free memory and felt querying the meminfo data source was helpful. This also helped us get a few more related parameters that were pre-parsed.

    Code

    import os
    
    linux_filepath = "/proc/meminfo"
    meminfo = dict(
        (i.split()[0].rstrip(":"), int(i.split()[1]))
        for i in open(linux_filepath).readlines()
    )
    meminfo["memory_total_gb"] = meminfo["MemTotal"] / (2 ** 20)
    meminfo["memory_free_gb"] = meminfo["MemFree"] / (2 ** 20)
    meminfo["memory_available_gb"] = meminfo["MemAvailable"] / (2 ** 20)
    

    Output for reference (we stripped all newlines for further analysis)

    MemTotal: 1014500 kB MemFree: 562680 kB MemAvailable: 646364 kB Buffers: 15144 kB Cached: 210720 kB SwapCached: 0 kB Active: 261476 kB Inactive: 128888 kB Active(anon): 167092 kB Inactive(anon): 20888 kB Active(file): 94384 kB Inactive(file): 108000 kB Unevictable: 3652 kB Mlocked: 3652 kB SwapTotal: 0 kB SwapFree: 0 kB Dirty: 0 kB Writeback: 0 kB AnonPages: 168160 kB Mapped: 81352 kB Shmem: 21060 kB Slab: 34492 kB SReclaimable: 18044 kB SUnreclaim: 16448 kB KernelStack: 2672 kB PageTables: 8180 kB NFS_Unstable: 0 kB Bounce: 0 kB WritebackTmp: 0 kB CommitLimit: 507248 kB Committed_AS: 1038756 kB VmallocTotal: 34359738367 kB VmallocUsed: 0 kB VmallocChunk: 0 kB HardwareCorrupted: 0 kB AnonHugePages: 88064 kB CmaTotal: 0 kB CmaFree: 0 kB HugePages_Total: 0 HugePages_Free: 0 HugePages_Rsvd: 0 HugePages_Surp: 0 Hugepagesize: 2048 kB DirectMap4k: 43008 kB DirectMap2M: 1005568 kB

    0 讨论(0)
  • 2020-11-22 05:05

    This script for CPU usage:

    import os
    
    def get_cpu_load():
        """ Returns a list CPU Loads"""
        result = []
        cmd = "WMIC CPU GET LoadPercentage "
        response = os.popen(cmd + ' 2>&1','r').read().strip().split("\r\n")
        for load in response[1:]:
           result.append(int(load))
        return result
    
    if __name__ == '__main__':
        print get_cpu_load()
    
    0 讨论(0)
  • 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])
    
    0 讨论(0)
提交回复
热议问题