Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current CPU and RAM usage in Python?

What's your preferred way of getting the current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for 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?

like image 374
lpfavreau Avatar asked Nov 09 '08 16:11

lpfavreau


People also ask

How do I see current RAM usage in Python?

The function psutil. virutal_memory() returns a named tuple about system memory usage. The third field in tuple represents the percentage use of the memory(RAM). It is calculated by (total – available)/total * 100 .

What is CPU in Python?

cpu_count() method in Python is used to get the number of CPUs in the system. This method returns None if number of CPUs in the system is undetermined. Syntax: os.cpu_count() Parameter: No parameter is required. Return Type: This method returns an integer value which denotes the number of CPUs in the system.


1 Answers

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/
like image 148
Jon Cage Avatar answered Sep 24 '22 02:09

Jon Cage