Psutil module in Python

Psutil is a Python cross-platform library used to access system details and process utilities. It is used to keep track of various resources utilization in the system. Usage of resources like CPU, memory, disks, network, sensors can be monitored. Hence, this library is used for system monitoring, profiling, limiting process resources and the management of running processes. It is supported in Python versions 2.6, 2.7 and 3.4+.

Installation Steps in Linux Ubuntu/Debian

sudo pip install psutil

System Functions

CPU

1) psutil.cpu_times() – This function gives system CPU times as a named tuple.

Parameters:

  • user – time spent by normal processes executing in user mode
  • system – time spent by processes executing in kernel mode
  • idle – time when system was idle
  • nice – time spent by priority processes executing in user mode
  • iowait – time spent waiting for I/O to complete. This is not accounted in idle time counter.
  • irq – time spent for servicing hardware interrupts
  • softirq – time spent for servicing software interrupts
  • steal – time spent by other operating systems running in a virtualized environment
  • guest – time spent running a virtual CPU for guest operating systems under the control of the Linux kernel

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print(psutil.cpu_times())

chevron_right


Output



scputimes(user=5461.14, nice=2.44, system=1326.65, idle=45502.33, iowait=506.24, irq=0.0, softirq=5.46, steal=0.0, guest=0.0, guest_nice=0.0)

2) psutil.cpu_percent(interval) – This function calculates the current system-wide CPU utilization as a percentage.It is recommended to provide time interval (seconds) as parameter to the function over which the average cpu usage will be calculated, ignoring the interval parameter could result in high variation in usage values.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
print(psutil.cpu_percent(1))

chevron_right


Output

5.0

3) psutil.cpu_count(logical=True) – This function shows a number of logical CPUs in the system. The logical core is calculated as the number of physical cores multiplied by the number of threads that can run on each core. In the absence of logical core, it only counts a number of physical cores.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print("Number of cores in system", psutil.cpu_count())
print("\nNumber of physical cores in system",)

chevron_right


Output:

Number of cores in system 4
Number of physical cores in system 2

4) psutil.cpu_stats() – This function gives CPU statistics as a named tuple. The statistics includes :



  • ctx_switches – number of context switches since boot.
  • interrupts – number of interrupts since boot.
  • soft_interrupts – number of software interrupts since boot.
  • syscalls – number of system calls since boot. Always set to 0 in Ubuntu.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print("CPU Statistics", psutil.cpu_stats())

chevron_right


scpustats(ctx_switches=37382771, interrupts=13744347, soft_interrupts=6769413, syscalls=0)

5) psutil.cpu_freq() – This function gives CPU frequency as a tuple that includes current, min and max frequencies expressed in Mhz. On Ubuntu current frequency reports the real-time value. Whereas on all other platforms it represents the nominal “fixed” value.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print(psutil.cpu_freq())

chevron_right


Output:

scpufreq(current=931.42925, min=400.0, max=2000.0)

6) psutil.getloadavg() – This function gives the average system load in last 1, 5 and 15 minutes as a tuple. The load represents the processes which are in a runnable state, either using the CPU or waiting to use the CPU (e.g. waiting for disk I/O).

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print(psutil.getloadavg())

chevron_right


Output:

(0.22, 0.33, 0.35)

Memory

1) psutil.virtual_memory() – This function gives system memory usage in bytes. The sum of used and available may or may not be equal to total. In order to get details of free physical memory this function is used.



Parameters:

  • total – total physical memory excluding swap.
  • available – the memory that can be given instantly to processes without the system going into swap.
  • used – memory used.
  • free – memory not used at and is readily available
  • active – memory currently in use or very recently used.
  • inactive – memory that is marked as not used.
  • buffers – cache data like file system metadata.
  • cached – cached data
  • shared – memory that may be accessed by multiple processes.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print(psutil.virtual_memory())

chevron_right


Output:

svmem(total=4028772352, available=1061466112, percent=73.7, used=2401546240, free=412352512, active=2176798720, inactive=1196470272, buffers=70774784, cached=1144098816, shared=313872384, slab=125116416)

2) psutil.swap_memory() – This function provides details of swap memory statistics as a tuple.

Parameters:

  • total – total swap memory in bytes
  • used – used swap memory in bytes
  • free – free swap memory in bytes
  • percent – the percentage usage that is calculated as (total – available) / total * 100
  • sin – the number of bytes the system has swapped in from disk
  • sout – the number of bytes the system has swapped out from disk

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print(psutil.swap_memory())

chevron_right


Output:

sswap(total=2097147904L, used=886620160L, free=1210527744L, percent=42.3, sin=1050411008, sout=1906720768)

Disks

1) psutil.disk_partitions() – This function provides the details of all mounted disk partitions as a list of tuples including device, mount point and filesystem type.



Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print(psutil.disk_partitions())

chevron_right


Output:

[sdiskpart(device=’/dev/sda1′, mountpoint=’/’, fstype=’ext4′, opts=’rw, relatime, errors=remount-ro, data=ordered’)]

2) psutil.disk_usage(path)- This function gives disk usage statistics as a tuple for a given path. Total, used and free space are expressed in bytes, along with the percentage usage.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print(psutil.disk_usage('/'))

chevron_right


Output:

sdiskusage(total=787310764032, used=26450710528, free=720843354112, percent=3.5)

Network

1) psutil.net_io_counters()- This function gives the details of network Input output statistics as a tuple.

Parameters:

  • bytes_sent – number of bytes sent
  • bytes_recv – number of bytes received
  • packets_sent – number of packets sent
  • packets_recv – number of packets received
  • errin – total number of errors while receiving
  • errout – total number of errors while sending
  • dropin – total number of incoming packets which were dropped
  • dropout – total number of outgoing packets which were dropped
Example :



filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print(psutil.net_io_counters())

chevron_right


Output:

snetio(bytes_sent=14508483, bytes_recv=62749361, packets_sent=84311, packets_recv=94888, errin=0, errout=0, dropin=0, dropout=0)

2) psutil.net_connections() – This function gives the list of socket connections of a system as a named tuples.

Parameters:

  • fd – the socket file descriptor.
  • family – the socket family, either AF_INET, AF_INET6 or AF_UNIX.
  • type – the socket type, either SOCK_STREAM, SOCK_DGRAM or SOCK_SEQPACKET.
  • laddr – the local address as a (ip, port) named tuple
  • raddr – the remote address as a (ip, port) named tuple
  • status – represents the status of a TCP connection.
  • pid – the PID of the process which opened the socket, if retrievable, else None.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print(psutil.net_connections())

chevron_right


Output:

[sconn(fd=118, family=2, type=1, laddr=addr(ip=’192.168.12.184′, port=59666), raddr=addr(ip=’172.217.166.42′, port=443), status=’ESTABLISHED’, pid=2428),
sconn(fd=-1, family=2, type=2, laddr=addr(ip=’0.0.0.0′, port=631), raddr=(), status=’NONE’, pid=None),
sconn(fd=-1, family=2, type=1, laddr=addr(ip=’127.0.0.1′, port=3306), raddr=(), status=’LISTEN’, pid=None),
sconn(fd=145, family=2, type=1, laddr=addr(ip=’192.168.12.184′, port=56568), raddr=addr(ip=’172.217.166.35′, port=443), status=’ESTABLISHED’, pid=2428),
sconn(fd=-1, family=2, type=2, laddr=addr(ip=’0.0.0.0′, port=52253), raddr=(), status=’NONE’, pid=None)]

3) psutil.net_if_addrs() – This function is used to get the addresses of each network interface card installed on the system. It is a dictionary whose keys are the Network Interface Card names and value is a list of named tuples for each address assigned to it. Each tuple includes:

  • family – the socket family, either AF_INET or AF_INET6
  • address – the primary NIC address
  • netmask – the netmask address
  • broadcast – the broadcast address.
  • ptp – “point to point” it is the destination address on a point to point interface.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print(psutil.net_if_addrs())

chevron_right


Output:



{‘wlo1′: [snicaddr(family=2, address=’192.168.12.184′, netmask=’255.255.255.0′, broadcast=’192.168.12.255′, ptp=None), snicaddr(family=10, address=’fe80::664f:767c:91f0:71c0%wlo1′, netmask=’ffff:ffff:ffff:ffff::’, broadcast=None, ptp=None), snicaddr(family=17, address=’3c:f8:62:32:b7:70′, netmask=None, broadcast=’ff:ff:ff:ff:ff:ff’, ptp=None)], ‘lo’: [snicaddr(family=2, address=’127.0.0.1′, netmask=’255.0.0.0′, broadcast=None, ptp=None), snicaddr(family=10, address=’::1′, netmask=’ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff’, broadcast=None, ptp=None), snicaddr(family=17, address=’00:00:00:00:00:00′, netmask=None, broadcast=None, ptp=None)], ‘docker0′: [snicaddr(family=2, address=’172.17.0.1′, netmask=’255.255.0.0′, broadcast=’172.17.255.255′, ptp=None), snicaddr(family=17, address=’02:42:ef:4c:3b:d9′, netmask=None, broadcast=’ff:ff:ff:ff:ff:ff’, ptp=None)], ‘eno1′: [snicaddr(family=17, address=’3c:52:82:09:8e:c2′, netmask=None, broadcast=’ff:ff:ff:ff:ff:ff’, ptp=None)]}

Sensors

1) psutil.sensors_temperatures()- This function returns hardware temperatures of the system in celsius. Each entry is a named tuple representing a certain hardware temperature sensor.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print(psutil.sensors_temperatures())

chevron_right


Output:

{‘acpitz’: [shwtemp(label=”, current=27.8, high=119.0, critical=119.0), shwtemp(label=”, current=29.8, high=119.0, critical=119.0), shwtemp(label=”, current=10.0, high=None, critical=None)], ‘coretemp’: [shwtemp(label=’Physical id 0′, current=42.0, high=100.0, critical=100.0), shwtemp(label=’Core 0′, current=41.0, high=100.0, critical=100.0), shwtemp(label=’Core 1′, current=41.0, high=100.0, critical=100.0), shwtemp(label=’Physical id 0′, current=42.0, high=100.0, critical=100.0), shwtemp(label=’Core 0′, current=41.0, high=100.0, critical=100.0), shwtemp(label=’Core 1′, current=41.0, high=100.0, critical=100.0)]}

2) psutil.sensors_fans() – This function gives the details of hardware fans speed expressed in RPM (rounds per minute). If sensors are not supported by the OS an empty dict is returned.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
print(psutil.sensors_fans())

chevron_right


Output:

{'asus': [sfan(label='cpu_fan', current=3000)]}

3) psutil.sensors_battery() – This function gives battery status information as a named tuple.

Parameters:



  • percent – battery power left as a percentage.
  • secsleft – an approximate time in seconds before battery is completely discharged.
  • power_plugged – True if the AC power cable is connected, False if it is not connected.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print(psutil.sensors_battery())

chevron_right


Output:

sbattery(percent=98.98572501878287, secsleft=22913, power_plugged=False)

Other system info

1) psutil.boot_time() – This function returns the system boot time which is expressed in seconds since the epoch.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil, datetime
  
  
print(psutil.boot_time())

chevron_right


Output:

1582860765.0

2) sutil.users() – This function gives the list of users who are connected on the system as a named tuples.
Parameters:

  • user – It is the system name of the user.
  • terminal – the tty of the user.
  • host – the host name of the user.
  • started – the creation time as a floating point number expressed in seconds since the epoch.
  • pid – the PID of the login process.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

import psutil
  
  
print(psutil.users())

chevron_right


Output:

[suser(name=’admin1′, terminal=’tty7′, host=’localhost’, started=1582860800.0, pid=1747)]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : shikharraizaday

Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.