How to get current CPU and RAM usage in Python?

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

    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:

    • https://psutil.readthedocs.io/en/latest/

提交回复
热议问题