psutil Python

Introduction

Psutil is a cross-platform Python library used to access system details and process utilities.

It is used to track the usage of various resources in the system.

You can control the usage of resources such as the processor, memory, disks, network, and sensors.

Consequently, this library is used for system monitoring, profiling, limiting the resources of processes and managing running processes.

It is supported in Python versions 2.6, 2.7 and 3.4+.

Installation

Usually it is enough to run

pip install psutil

But it is better (*)

python3 -m pip install psutil

Before that, of course, you need to install Python and Pip

A simple example

In Linux you can get some of this even without psutil

import platform print(platform.processor())

x86_64

CPU

To collect information about the CPU you need to import psutil

import psutil print(psutil.cpu_times())

x86_64
scputimes(user=11137.09, nice=1105.78, system=3347.08, idle=164460.53, iowait=135.55, irq=0.0, softirq=46.12, steal=0.0, guest=0.0, guest_nice=0.0)

An example script that writes the time, the CPU and RAM to the file log.txt

#!/usr/bin/python3 import psutil import datetime dt_now = str(datetime.datetime.now()) cpu = str(psutil.cpu_percent(interval=0.2)) ram = str((psutil.virtual_memory().available * 100 / psutil.virtual_memory().total)) with open('log.txt', 'a') as f: f.write(dt_now+";"+cpu+";"+ram+"\n")

Article author: Andrei Olegovich