Search code examples
pythonsystemcpustatusram

How to get current CPU and RAM usage in Python?


How can I get the current system status (current CPU, RAM, free disk space, etc.) in Python? Ideally, it would work for both Unix and Windows platforms.

There seems to be a few possible ways of extracting that from my search:

  1. Using a library such as PSI (that currently seems not actively developed and not supported on multiple platforms) or something like pystatgrab (again no activity since 2007 it seems and no support for Windows).

  2. Using platform specific code such as using a os.popen("ps") or similar for the *nix systems and MEMORYSTATUS in ctypes.windll.kernel32 (see this recipe on ActiveState) for the Windows platform. One could put a Python class together with all those code snippets.

It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?


Solution

  • The psutil library gives you information about CPU, RAM, etc., on a variety of platforms:

    psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by tools like ps, top and Windows task manager.

    It currently supports Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.5 (users of Python 2.4 and 2.5 may use 2.1.3 version).


    Some examples:

    #!/usr/bin/env python
    import psutil
    # gives a single float value
    psutil.cpu_percent()
    # gives an object with many fields
    psutil.virtual_memory()
    # you can convert that object to a dictionary 
    dict(psutil.virtual_memory()._asdict())
    # you can have the percentage of used RAM
    psutil.virtual_memory().percent
    79.2
    # you can calculate percentage of available memory
    psutil.virtual_memory().available * 100 / psutil.virtual_memory().total
    20.8
    

    Here's other documentation that provides more concepts and interest concepts: