Convert Figma logo to code with AI

giampaolo logopsutil

Cross-platform lib for process and system monitoring in Python

11,226
1,493
11,226
394

Top Related Projects

32,878

Glances an Eye on your system. A top/htop alternative for GNU/Linux, BSD, Mac OS and Windows operating systems.

5,904

htop is an interactive text-mode process viewer for Unix systems. It aims to be a better 'top'.

32,940

A monitor of resources

Exporter for machine metrics

79,770

The fastest path to AI-powered full stack observability, even for lean teams.

23,394

SQL powered operating system instrumentation, monitoring, and analytics.

Quick Overview

psutil (Python System and Process Utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python. It is useful for system monitoring, profiling, limiting process resources, and managing running processes.

Pros

  • Cross-platform compatibility (Windows, Linux, macOS, FreeBSD, OpenBSD, NetBSD, Sun Solaris, AIX)
  • Extensive system and process information retrieval capabilities
  • Easy-to-use API with Pythonic interface
  • Actively maintained with regular updates and improvements

Cons

  • Some advanced features may require elevated privileges
  • Performance can be impacted when dealing with a large number of processes
  • Occasional discrepancies in reported values due to differences in underlying OS implementations
  • Limited support for some less common operating systems

Code Examples

  1. Getting CPU usage percentage:
import psutil

cpu_percent = psutil.cpu_percent(interval=1)
print(f"CPU usage: {cpu_percent}%")
  1. Listing all running processes:
import psutil

for proc in psutil.process_iter(['pid', 'name', 'username']):
    print(proc.info)
  1. Getting memory usage information:
import psutil

memory = psutil.virtual_memory()
print(f"Total memory: {memory.total / (1024 * 1024):.2f} MB")
print(f"Available memory: {memory.available / (1024 * 1024):.2f} MB")
print(f"Memory usage: {memory.percent}%")
  1. Monitoring disk usage:
import psutil

disk = psutil.disk_usage('/')
print(f"Total disk space: {disk.total / (1024 * 1024 * 1024):.2f} GB")
print(f"Used disk space: {disk.used / (1024 * 1024 * 1024):.2f} GB")
print(f"Free disk space: {disk.free / (1024 * 1024 * 1024):.2f} GB")
print(f"Disk usage: {disk.percent}%")

Getting Started

To get started with psutil, first install it using pip:

pip install psutil

Then, you can import and use psutil in your Python scripts:

import psutil

# Get system-wide CPU usage
cpu_percent = psutil.cpu_percent(interval=1)
print(f"CPU usage: {cpu_percent}%")

# Get memory usage
memory = psutil.virtual_memory()
print(f"Memory usage: {memory.percent}%")

# Get disk usage
disk = psutil.disk_usage('/')
print(f"Disk usage: {disk.percent}%")

This basic example demonstrates how to retrieve CPU, memory, and disk usage information using psutil.

Competitor Comparisons

32,878

Glances an Eye on your system. A top/htop alternative for GNU/Linux, BSD, Mac OS and Windows operating systems.

Pros of Glances

  • Provides a user-friendly, curses-based interface for system monitoring
  • Offers a web-based interface for remote monitoring
  • Includes built-in alert system and export capabilities

Cons of Glances

  • More resource-intensive due to its comprehensive interface
  • Less flexible for integration into custom scripts or applications
  • Steeper learning curve for customization and extension

Code Comparison

Psutil (retrieving CPU usage):

import psutil
cpu_percent = psutil.cpu_percent(interval=1)
print(f"CPU usage: {cpu_percent}%")

Glances (retrieving CPU usage):

from glances_api import GlancesApi
client = GlancesApi(url='http://localhost:61208')
cpu_percent = client.getCpu()['total']
print(f"CPU usage: {cpu_percent}%")

Summary

Psutil is a lightweight, versatile library for accessing system information, ideal for integration into custom scripts and applications. Glances, built on top of Psutil, provides a more comprehensive, user-friendly monitoring solution with additional features like a web interface and alerting system. While Glances offers a more complete out-of-the-box monitoring experience, Psutil provides greater flexibility and efficiency for developers needing direct access to system metrics.

5,904

htop is an interactive text-mode process viewer for Unix systems. It aims to be a better 'top'.

Pros of htop

  • Interactive and user-friendly terminal-based interface
  • Real-time system monitoring with colorful and detailed display
  • Ability to send signals to processes directly from the interface

Cons of htop

  • Limited to Unix-like systems (not cross-platform)
  • Primarily designed for interactive use, less suitable for scripting or automation
  • Focused on system monitoring, lacks extensive programmatic access to system information

Code Comparison

htop (C):

void Process_writeCommand(Process* this, int attr) {
    int baseattr = attr;
    RichString_begin(out);
    RichString_appendWide(&out, baseattr, this->comm);
    RichString_end(out);
}

psutil (Python):

def cpu_percent(interval=None, percpu=False):
    if interval is None:
        return _psutil_linux.cpu_percent(percpu)
    else:
        return _psutil_linux.cpu_percent_interval(interval, percpu)

Key Differences

  • htop is a standalone application, while psutil is a library for system monitoring
  • htop provides a visual interface, psutil offers programmatic access to system information
  • htop is written in C, psutil is primarily written in Python with C extensions
  • psutil is cross-platform, supporting Windows, macOS, and various Unix-like systems
  • psutil offers more extensive API for accessing detailed system and process information
32,940

A monitor of resources

Pros of btop

  • Provides a visually appealing and interactive terminal-based resource monitor
  • Offers customizable themes and layout options for a better user experience
  • Includes battery and temperature monitoring features

Cons of btop

  • Limited to system monitoring and visualization, not a general-purpose library
  • May have higher resource usage due to its graphical interface
  • Less cross-platform compatibility compared to psutil

Code comparison

psutil:

import psutil

cpu_percent = psutil.cpu_percent()
memory = psutil.virtual_memory()
disk = psutil.disk_usage('/')

btop:

void Cpu::update_cpus() {
    for (auto& [cpu_id, cpu] : cpus) {
        cpu.usage = get_cpu_usage(cpu_id);
    }
}

Summary

psutil is a cross-platform library for retrieving information on running processes and system utilization, while btop is a resource monitor and task manager application with a rich terminal user interface. psutil is more suitable for programmatic system monitoring and automation tasks, whereas btop excels in providing an interactive and visually appealing system monitoring experience for end-users.

Exporter for machine metrics

Pros of node_exporter

  • Designed specifically for Prometheus monitoring ecosystem
  • Provides a wide range of exporters for various system metrics
  • Easily integrates with Prometheus for centralized monitoring

Cons of node_exporter

  • Limited to Linux and Unix-like systems
  • Requires additional setup and configuration with Prometheus
  • Less flexible for standalone use or integration with other tools

Code Comparison

node_exporter (Go):

func (c *cpuCollector) Update(ch chan<- prometheus.Metric) error {
    times, err := cpu.Times(false)
    if err != nil {
        return err
    }
    for _, t := range times {
        ch <- prometheus.MustNewConstMetric(c.cpu, prometheus.CounterValue, t.User, t.CPU)
    }
    return nil
}

psutil (Python):

def cpu_times(percpu=False):
    ret = []
    for cpu in range(psutil.cpu_count()) if percpu else [None]:
        st = _psutil_windows.cpu_times(cpu)
        ret.append(scputimes(*st))
    return ret[0] if not percpu else ret

Both repositories provide system and process utilities, but node_exporter is tailored for Prometheus monitoring, while psutil offers a more general-purpose library for system information retrieval across multiple platforms.

79,770

The fastest path to AI-powered full stack observability, even for lean teams.

Pros of netdata

  • Provides a comprehensive, real-time monitoring solution with a web-based dashboard
  • Offers automatic alerting and notification features
  • Includes built-in visualization and reporting tools

Cons of netdata

  • Requires more system resources due to its full-featured nature
  • Has a steeper learning curve for configuration and customization
  • May be overkill for simple monitoring tasks or resource-constrained environments

Code comparison

netdata (JavaScript):

var netdata = {
    options: { current: {} },
    chartRegistry: {},
    charts: {},
    globals: {
        chart_resolution: 0,
        server_timezone: 'unknown'
    }
};

psutil (Python):

import psutil

cpu_percent = psutil.cpu_percent()
memory = psutil.virtual_memory()
disk = psutil.disk_usage('/')

netdata provides a more comprehensive monitoring solution with a web-based interface, while psutil offers a lightweight, cross-platform library for system and process monitoring. netdata is better suited for full-scale monitoring and visualization, whereas psutil is ideal for programmatic access to system information and integration into custom applications.

23,394

SQL powered operating system instrumentation, monitoring, and analytics.

Pros of osquery

  • More comprehensive system information gathering, including network, hardware, and security data
  • SQL-based querying interface for flexible and powerful data retrieval
  • Cross-platform support for Windows, macOS, and Linux

Cons of osquery

  • Heavier resource footprint and more complex setup
  • Steeper learning curve due to SQL syntax and extensive schema
  • Less suitable for simple, quick system information retrieval

Code Comparison

osquery:

SELECT * FROM processes WHERE name = 'chrome';

psutil:

import psutil
[p for p in psutil.process_iter() if p.name() == 'chrome']

Key Differences

  • osquery provides a SQL interface for querying system information, while psutil offers a Python API
  • osquery is more suited for large-scale system monitoring and security analysis, whereas psutil is better for quick, programmatic access to system resources
  • psutil is more lightweight and easier to integrate into Python projects, while osquery offers more extensive data collection capabilities

Both tools are valuable for system monitoring and management, but they cater to different use cases and skill levels. osquery is more powerful for complex queries and large-scale deployments, while psutil is more accessible for Python developers and simpler system resource monitoring tasks.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

..

.. raw:: html

<div align="center">
    <a href="https://github.com/giampaolo/psutil"><img src="https://github.com/giampaolo/psutil/raw/master/docs/_static/images/logo-psutil-readme.svg" alt="psutil" /></a>
    <p align="center">Process and System Utilities for Python</p>
    <a href="https://psutil.readthedocs.io/"><b>Documentation</b></a>&nbsp;&nbsp;&nbsp;
    <a href="https://psutil.readthedocs.io/latest/blog.html"><b>Blog</b></a>&nbsp;&nbsp;&nbsp;
    <a href="https://psutil.readthedocs.io/latest/adoption.html"><b>Who uses psutil</b></a>&nbsp;&nbsp;&nbsp;
</div>

<br/>

<div align="center">
  <a href="https://clickpy.clickhouse.com/dashboard/psutil">
    <img src="https://static.pepy.tech/badge/psutil/month" alt="Downloads">
  </a>

  <a href="https://repology.org/metapackage/python:psutil/versions">
    <img src="https://repology.org/badge/tiny-repos/python:psutil.svg" alt="Binary packages">
  </a>

  <a href="https://pypi.org/project/psutil">
    <img src="https://img.shields.io/pypi/v/psutil.svg?label=pypi&color=yellowgreen" alt="Latest version">
  </a>

  <a href="https://github.com/giampaolo/psutil/actions?query=workflow%3Abuild">
    <img src="https://img.shields.io/github/actions/workflow/status/giampaolo/psutil/.github/workflows/build.yml.svg?label=Linux%2C%20macOS%2C%20Win" alt="Linux, macOS, Windows">
  </a>

  <a href="https://github.com/giampaolo/psutil/actions?query=workflow%3Absd-tests">
    <img src="https://img.shields.io/github/actions/workflow/status/giampaolo/psutil/.github/workflows/bsd.yml.svg?label=BSD" alt="FreeBSD, NetBSD, OpenBSD">
  </a>
</div>

..

About

psutil is a cross-platform library for retrieving information about running processes and system utilization (CPU, memory, disks, network, sensors) in Python. It is useful mainly for system monitoring, profiling, limiting process resources, and managing running processes.

It implements many functionalities offered by UNIX command line tool such as ps, top, free, iotop, netstat, ifconfig, lsof and others (see shell equivalents_). psutil supports the following platforms:

  • Linux
  • Windows
  • macOS
  • FreeBSD, OpenBSD, NetBSD
  • Sun Solaris
  • AIX

Adoption

psutil is among the top 100 <https://clickpy.clickhouse.com/dashboard/psutil>__ most-downloaded packages on PyPI, with 330+ million downloads per month, 760,000+ GitHub repositories <https://github.com/giampaolo/psutil/network/dependents>__ using it, and 15,000+ packages depending on it.

See also adoptions <https://psutil.readthedocs.io/latest/adoption.html>__ and alternatives <https://psutil.readthedocs.io/latest/alternatives.html>__.

Install

.. code-block::

pip install psutil

For platform-specific details see installation <https://psutil.readthedocs.io/latest/install.html>_.

Documentation

psutil documentation is available at https://psutil.readthedocs.io/latest.

..

Sponsors

.. raw:: html

<table border="0" cellpadding="10" cellspacing="0" class="sponsor-table">
  <tr>
    <td align="center" style="vertical-align: middle;">
      <a href="https://tidelift.com/subscription/pkg/pypi-psutil?utm_source=pypi-psutil&utm_medium=referral&utm_campaign=readme">
        <img width="160" src="https://raw.githubusercontent.com/giampaolo/psutil/refs/heads/master/docs/_static/images/logo-tidelift.svg" class="sponsor-logo">
      </a>
    </td>
    <td align="center" style="vertical-align: middle;">
      <a href="https://sansec.io/">
        <img width="145" src="https://raw.githubusercontent.com/giampaolo/psutil/refs/heads/master/docs/_static/images/logo-sansec.svg" class="sponsor-logo">
      </a>
    </td>
    <td align="center" style="vertical-align: middle;">
      <a href="https://www.apivoid.com/">
        <img width="130" src="https://raw.githubusercontent.com/giampaolo/psutil/refs/heads/master/docs/_static/images/logo-apivoid.svg" class="sponsor-logo">
      </a>
    </td>
  </tr>
</table>

<div style="text-align: center;"><sup><a href="https://psutil.readthedocs.io/latest/funding.html">add your logo</a></sup></div>

..

Example usages

For the full API with more examples, see the API overview <https://psutil.readthedocs.io/latest/api-overview.html>_ and API reference <https://psutil.readthedocs.io/latest/api.html>_.

CPU

.. code-block:: python

>>> import psutil
>>> psutil.cpu_percent(interval=1, percpu=True)
[4.0, 6.9, 3.7, 9.2]
>>> psutil.cpu_count(logical=False)
2
>>> psutil.cpu_freq()
scpufreq(current=931.42, min=800.0, max=3500.0)

Memory

.. code-block:: python

>>> psutil.virtual_memory()
svmem(total=10367352832, available=6472179712, percent=37.6, used=8186245120, free=2181107712, ...)
>>> psutil.swap_memory()
sswap(total=2097147904, used=296128512, free=1801019392, percent=14.1, sin=304193536, sout=677842944)

Disks

.. code-block:: python

>>> psutil.disk_partitions()
[sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid'),
 sdiskpart(device='/dev/sda2', mountpoint='/home', fstype='ext', opts='rw')]
>>> psutil.disk_usage('/')
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)

Network

.. code-block:: python

>>> psutil.net_io_counters(pernic=True)
{'eth0': netio(bytes_sent=485291293, bytes_recv=6004858642, ...),
 'lo': netio(bytes_sent=2838627, bytes_recv=2838627, ...)}
>>> psutil.net_connections(kind='tcp')
[sconn(fd=115, family=2, type=1, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED', pid=1254),
 ...]

Sensors

.. code-block:: python

>>> psutil.sensors_temperatures()
{'coretemp': [shwtemp(label='Physical id 0', current=52.0, high=100.0, critical=100.0),
              shwtemp(label='Core 0', current=45.0, high=100.0, critical=100.0)]}
>>> psutil.sensors_battery()
sbattery(percent=93, secsleft=16628, power_plugged=False)

Processes

.. code-block:: python

>>> p = psutil.Process(7055)
>>> p.name()
'python3'
>>> p.exe()
'/usr/bin/python3'
>>> p.cpu_percent(interval=1.0)
12.1
>>> p.memory_info()
pmem(rss=3164160, vms=4410163, shared=897433, text=302694, data=2422374)
>>> p.net_connections(kind='tcp')
[pconn(fd=115, family=2, type=1, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED')]
>>> p.open_files()
[popenfile(path='/home/giampaolo/monit.py', fd=3, position=0, mode='r', flags=32768)]
>>>
>>> for p in psutil.process_iter(['pid', 'name']):
...     print(p.pid, p.name())
...
1 systemd
2 kthreadd
3 ksoftirqd/0
...

.. _shell equivalents: https://psutil.readthedocs.io/latest/shell-equivalents.html

..

License

BSD-3