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:
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).
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?
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 .
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With