How to get current CPU and RAM usage in Python?

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

    Use the psutil library. On Ubuntu 18.04, pip installed 5.5.0 (latest version) as of 1-30-2019. Older versions may behave somewhat differently. You can check your version of psutil by doing this in Python:

    from __future__ import print_function  # for Python2
    import psutil
    print(psutil.__versi‌​on__)
    

    To get some memory and CPU stats:

    from __future__ import print_function
    import psutil
    print(psutil.cpu_percent())
    print(psutil.virtual_memory())  # physical memory usage
    print('memory % used:', psutil.virtual_memory()[2])
    

    The virtual_memory (tuple) will have the percent memory used system-wide. This seemed to be overestimated by a few percent for me on Ubuntu 18.04.

    You can also get the memory used by the current Python instance:

    import os
    import psutil
    pid = os.getpid()
    py = psutil.Process(pid)
    memoryUse = py.memory_info()[0]/2.**30  # memory use in GB...I think
    print('memory use:', memoryUse)
    

    which gives the current memory use of your Python script.

    There are some more in-depth examples on the pypi page for psutil.

提交回复
热议问题