Operations 23 min read

Using psutil to Retrieve System and Process Information in Python

This article demonstrates how to install the psutil Python library and use it to gather detailed CPU, memory, disk, network, and process information on a system, providing code examples and explanations for each type of metric.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Using psutil to Retrieve System and Process Information in Python

psutil is a third‑party Python module that provides functions for retrieving operating‑system and hardware information such as CPU, disk, network, and memory statistics.

First, install it with pip install psutil and then explore its usage.

CPU Related

Get the logical CPU count:

import psutil
print(psutil.cpu_count())  # e.g., 12

Get the physical core count:

import psutil
print(psutil.cpu_count(logical=False))  # e.g., 6
The result 6 indicates 6 physical cores with hyper‑threading; if physical and logical counts are equal (e.g., 12), it means 12 cores without hyper‑threading.

Show CPU times (user/system/idle):

import psutil
print(psutil.cpu_times())
# scputimes(user=..., system=..., idle=..., interrupt=..., dpc=...)
The return value is a namedtuple , and many other structures in psutil follow the same pattern.

Get per‑CPU usage percentages:

import psutil
for _ in range(3):
    print(psutil.cpu_percent(interval=0.5, percpu=True))
    # example output: [6.1, 6.2, 9.4, ...]

Show CPU statistics such as context switches and interrupts:

import psutil
print(psutil.cpu_stats())
# scpustats(ctx_switches=..., interrupts=..., soft_interrupts=..., syscalls=...)

Get CPU frequency information:

import psutil
print(psutil.cpu_freq())
# scpufreq(current=2208.0, min=0.0, max=2208.0)

Memory Related

View virtual memory usage:

import psutil
print(psutil.virtual_memory())
# svmem(total=..., available=..., percent=..., used=..., free=...)

total : total memory

available : available memory

percent : memory usage percentage

used : used memory

View swap memory information:

import psutil
print(psutil.swap_memory())
# sswap(total=..., used=..., free=..., percent=..., sin=0, sout=0)
Physical memory is the RAM installed in the machine; swap memory is disk space used when RAM is insufficient, acting like a temporary storage area for overflow data.

Disk Related

List disk partitions and their usage:

from pprint import pprint
import psutil
pprint(psutil.disk_partitions())
# [sdiskpart(device='C:\', mountpoint='C:\', fstype='NTFS', opts='rw,fixed'), ...]

Check usage of a specific partition:

import psutil
print(psutil.disk_usage("C:\"))
# sdiskusage(total=..., used=..., free=..., percent=...)

Get overall disk I/O counters:

from pprint import pprint
import psutil
pprint(psutil.disk_io_counters())
# sdiskio(read_count=..., write_count=..., read_bytes=..., write_bytes=..., read_time=..., write_time=...)

Get per‑disk I/O statistics:

from pprint import pprint
import psutil
pprint(psutil.disk_io_counters(perdisk=True))
# {'PhysicalDrive0': sdiskio(...), 'PhysicalDrive1': sdiskio(...)}

Network Related

Show network I/O statistics:

from pprint import pprint
import psutil
pprint(psutil.net_io_counters())
# snetio(bytes_sent=..., bytes_recv=..., packets_sent=..., packets_recv=..., errin=..., errout=..., dropin=..., dropout=...)

List network interfaces and their addresses:

from pprint import pprint
import psutil
pprint(psutil.net_if_addrs())
# {'WLAN': [snicaddr(family=AddressFamily.AF_LINK, address='04-...'), snicaddr(family=AddressFamily.AF_INET, address='192.168.8.115', netmask='255.255.255.0'), ...]}

Show interface status (up/down, speed, MTU):

from pprint import pprint
import psutil
pprint(psutil.net_if_stats())
# {'WLAN': snicstats(isup=True, duplex=NicDuplex.NIC_DUPLEX_FULL, speed=866, mtu=1500), ...}

List current network connections:

from pprint import pprint
import psutil
pprint(psutil.net_connections())
# [sconn(fd=-1, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, laddr=addr(ip='0.0.0.0', port=1024), raddr=(), status='LISTEN', pid=940), ...]

Process Management

Retrieve all process IDs:

from pprint import pprint
import psutil
pprint(psutil.pids())
# [0, 4, 144, 512, ...]

Check whether a specific PID exists:

from pprint import pprint
import psutil
pprint(psutil.pid_exists(22333))  # False
pprint(psutil.pid_exists(0))      # True

Iterate over all processes:

from pprint import pprint
import psutil
pprint(psutil.process_iter())
# <generator object process_iter at ...>

Get a Process object for a given PID and inspect its attributes:

import psutil
p = psutil.Process(pid=16948)
print(p.name())          # WeChat.exe
print(p.exe())           # D:\WeChat\WeChat.exe
print(p.cwd())           # D:\WeChat
print(p.cmdline())      # ['D:\WeChat\WeChat.exe']
print(p.pid)            # 16948
print(p.ppid())          # 11700
print(p.parent())        # psutil.Process(pid=11700, name='explorer.exe', ...)
print(p.children())      # [psutil.Process(pid=17452, name='WeChatWeb.exe', ...), ...]
print(p.status())        # running
print(p.username())     # LAPTOP-264ORES3\satori
print(p.create_time())   # 1561775539.0
print(p.cpu_times())     # pcputimes(user=..., system=..., ...)
print(p.memory_info())    # pmem(rss=..., vms=..., ...)
print(p.open_files())    # [popenfile(path='C:\...', fd=-1), ...]
print(p.connections())   # [pconn(fd=-1, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, laddr=addr(...), raddr=addr(...), status='ESTABLISHED'), ...]
print(p.num_threads())    # 66
print(p.threads())        # [pthread(id=13340, user_time=113.328125, system_time=179.015625), ...]
print(p.environ())        # {'PATH': 'C:\Program Files\...', 'USERNAME': 'satori', ...}

Terminate a process (example omitted for safety):

# p.terminate()  # would stop the WeChat process

Use psutil.test() to simulate the Unix ps command and display a snapshot of running processes.

import psutil
psutil.test()
# (output similar to the classic "ps" listing)

Finally, you can iterate over process_iter() to locate a process by name and obtain its PID, then manipulate it as needed.

import psutil
for proc in psutil.process_iter():
    if proc.name().lower() == "wechat.exe":
        print(proc.pid)
        # 16948

Conclusion

Overall, psutil is a powerful and easy‑to‑use library that provides extensive low‑level system information, making it valuable for monitoring, diagnostics, and automation tasks.

pythonprocess managementNetworkCPUMemorysystem monitoringpsutil
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.