diff --git a/aiprompts/libtmux_python.md b/aiprompts/libtmux_python.md new file mode 100644 index 0000000..437a4f8 --- /dev/null +++ b/aiprompts/libtmux_python.md @@ -0,0 +1,1762 @@ + +======================== +CODE SNIPPETS +======================== +TITLE: Initial Project Setup and Dependency Installation +DESCRIPTION: Steps to clone the `libtmux` repository, navigate into the project directory, and install all development dependencies using the `uv` package manager, including optional extras. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/developing.md#_snippet_0 + +LANGUAGE: console +CODE: +``` +$ git clone https://github.com/tmux-python/libtmux.git +``` + +LANGUAGE: console +CODE: +``` +$ cd libtmux +``` + +LANGUAGE: console +CODE: +``` +$ uv sync --all-extras --dev +``` + +---------------------------------------- + +TITLE: Install libtmux via pip +DESCRIPTION: Installs the libtmux library for the current user using pip. This is the standard installation method for stable releases. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_0 + +LANGUAGE: console +CODE: +``` +$ pip install --user libtmux +``` + +---------------------------------------- + +TITLE: Install libtmux developmental releases +DESCRIPTION: Installs pre-release versions (alpha, beta, release candidates) of libtmux using pip. This command is useful for testing new features before their general availability. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_1 + +LANGUAGE: console +CODE: +``` +$ pip install --user --upgrade --pre libtmux +``` + +---------------------------------------- + +TITLE: Install ptpython for command-line completion +DESCRIPTION: Installs ptpython, an interactive Python shell, to provide enhanced command-line completion for Python development. This is particularly useful when interacting with libtmux. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_4 + +LANGUAGE: console +CODE: +``` +$ pip install --user ptpython +``` + +---------------------------------------- + +TITLE: Install libtmux from Git trunk +DESCRIPTION: Installs libtmux directly from its Git repository's trunk in editable mode. This provides the very latest, potentially unstable, development version for active development or testing. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_2 + +LANGUAGE: console +CODE: +``` +$ pip install --user -e git+https://github.com/tmux-python/libtmux.git#egg=libtmux +``` + +---------------------------------------- + +TITLE: Building and Serving Project Documentation +DESCRIPTION: Instructions for generating and serving the project documentation using Sphinx and `sphinx-autobuild`. Commands cover starting a preview server, manual builds, and continuous rebuilding with a watch mode (requires `entr`). + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/developing.md#_snippet_2 + +LANGUAGE: console +CODE: +``` +$ make start_docs +``` + +LANGUAGE: console +CODE: +``` +$ make start +``` + +LANGUAGE: console +CODE: +``` +$ cd docs/ +$ make html +``` + +LANGUAGE: console +CODE: +``` +$ make serve +``` + +LANGUAGE: console +CODE: +``` +$ make build_docs +``` + +LANGUAGE: console +CODE: +``` +$ make serve_docs +``` + +LANGUAGE: console +CODE: +``` +$ make watch_docs +``` + +LANGUAGE: console +CODE: +``` +$ make dev_docs +``` + +---------------------------------------- + +TITLE: Start a new tmux session +DESCRIPTION: Initiates a new tmux session with a specified session name ('foo') and window name ('bar'). This command creates the initial environment for subsequent libtmux interactions. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_3 + +LANGUAGE: console +CODE: +``` +$ tmux new-session -n bar -s foo +``` + +---------------------------------------- + +TITLE: Starting tmux and Python for libtmux interaction +DESCRIPTION: This snippet demonstrates the initial setup required to interact with libtmux. It involves starting a tmux server in one terminal and then launching a Python interpreter in another to import the libtmux library. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/api/properties.md#_snippet_0 + +LANGUAGE: console +CODE: +``` +$ tmux +``` + +LANGUAGE: console +CODE: +``` +$ python +``` + +LANGUAGE: python +CODE: +``` +>>> import libtmux +``` + +---------------------------------------- + +TITLE: Launch ptpython interactive shell +DESCRIPTION: Starts the ptpython interactive Python shell. This shell offers features like command-line completion for a more efficient and user-friendly development experience. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_5 + +LANGUAGE: console +CODE: +``` +$ ptpython +``` + +---------------------------------------- + +TITLE: libtmux Python API Reference +DESCRIPTION: Key methods for interacting with tmux sessions, windows, and panes using the libtmux library. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_21 + +LANGUAGE: APIDOC +CODE: +``` +Session Class Methods: + new_window(attach=True, window_name=None) + - Creates a new tmux window. + - Parameters: + - attach: (bool) If False, creates in background. + - window_name: (str) Optional name for the window. + - Returns: Window object. + + kill_window(target) + - Kills a tmux window. + - Parameters: + - target: (str) Can be window_id (e.g., @2) or window_name (e.g., 'ha in the bg'). + + active_window() + - Returns the currently active Window object. + + windows + - Property to access a list of Window objects. + + windows.filter() + - Method to filter the list of Window objects. + +Window Class Methods: + kill() + - Kills the specific window object. + + split(attach=True) + - Splits the window into a new pane. + - Parameters: + - attach: (bool) If False, creates in background without switching cursor. + - Returns: Pane object. + + rename_window(new_name) + - Renames the window. + - Parameters: + - new_name: (str) The new name for the window. + +Pane Class Methods: + select() + - Selects (moves cursor to) the pane. + + send_keys(keys, enter=True, suppress_history=False) + - Sends keys to the pane. + - Parameters: + - keys: (str) The string of keys to send. + - enter: (bool) If True, presses Enter after sending keys. + - suppress_history: (bool) If True, prevents command from appearing in shell history. + + enter() + - Sends an Enter keypress to the pane. +``` + +---------------------------------------- + +TITLE: Getting the active tmux window with libtmux +DESCRIPTION: Demonstrates how to retrieve the currently active `Window` object from the session using `session.active_window`. This allows for subsequent manipulation of the current window. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_16 + +LANGUAGE: python +CODE: +``` +window = session.active_window +``` + +---------------------------------------- + +TITLE: Launch ptpython Interactive Shell +DESCRIPTION: Shows how to start the `ptpython` interactive shell after its installation. This command initiates the enhanced Python environment for interactive coding and testing. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_3 + +LANGUAGE: console +CODE: +``` +ptpython +``` + +---------------------------------------- + +TITLE: Install libtmux Python Library +DESCRIPTION: Instructions on how to install the `libtmux` Python library using pip. This command installs the package for the current user, making it available for Python scripts and interactive shells. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_0 + +LANGUAGE: console +CODE: +``` +pip install --user libtmux +``` + +---------------------------------------- + +TITLE: Initialize libtmux Server object +DESCRIPTION: Imports the libtmux library and creates a Server object. This object serves as the primary interface for interacting with the tmux server, allowing control over sessions, windows, and panes. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_6 + +LANGUAGE: python +CODE: +``` +import libtmux +server = libtmux.Server() +server +``` + +---------------------------------------- + +TITLE: Execute raw tmux commands and instantiate objects +DESCRIPTION: Illustrates direct execution of tmux commands via `cmd()` methods on `Server`, `Session`, and `Window` objects to create new sessions, windows, and panes. Also demonstrates how to construct `Window` and `Pane` objects from their respective IDs returned by these raw commands. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_7 + +LANGUAGE: python +CODE: +``` +server.cmd('new-session', '-d', '-P', '-F#{session_id}').stdout[0] +``` + +LANGUAGE: python +CODE: +``` +session.cmd('new-window', '-P').stdout[0] +``` + +LANGUAGE: python +CODE: +``` +Window.from_window_id(window_id=session.cmd('new-window', '-P', '-F#{window_id}').stdout[0], server=session.server) +``` + +LANGUAGE: python +CODE: +``` +window.cmd('split-window', '-P', '-F#{pane_id}').stdout[0] +``` + +LANGUAGE: python +CODE: +``` +Pane.from_pane_id(pane_id=window.cmd('split-window', '-P', '-F#{pane_id}').stdout[0], server=window.server) +``` + +---------------------------------------- + +TITLE: Install libtmux Python package +DESCRIPTION: This console command uses `pip` to install the `libtmux` library, which includes the pytest plugin and its associated fixtures, making them available for use in Python testing environments. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/pytest-plugin/index.md#_snippet_0 + +LANGUAGE: console +CODE: +``` +pip install libtmux +``` + +---------------------------------------- + +TITLE: Killing a tmux window directly from its object +DESCRIPTION: Illustrates how to obtain a `Window` object and then call its `kill()` method directly to close it. This provides an object-oriented way to manage windows. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_15 + +LANGUAGE: python +CODE: +``` +window = session.new_window(attach=False, window_name="check this out") +window +``` + +LANGUAGE: python +CODE: +``` +window.kill() +``` + +---------------------------------------- + +TITLE: List all tmux sessions +DESCRIPTION: Retrieves a list of all active tmux sessions as `Session` objects using `server.sessions`. This provides an overview of currently running tmux environments accessible through the libtmux Server object. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_8 + +LANGUAGE: python +CODE: +``` +server.sessions +``` + +---------------------------------------- + +TITLE: Access a specific session from the list +DESCRIPTION: Demonstrates accessing a specific `Session` object from the list returned by `server.sessions`, typically the first one. Note that the index is not guaranteed to be consistent if sessions are created or destroyed. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_9 + +LANGUAGE: python +CODE: +``` +server.sessions[0] +``` + +---------------------------------------- + +TITLE: Install ptpython for Enhanced Python Shell +DESCRIPTION: Provides the command to install `ptpython`, an interactive Python shell. `ptpython` offers advanced features like autocompletion and syntax highlighting, enhancing the development experience. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_2 + +LANGUAGE: console +CODE: +``` +pip install --user ptpython +``` + +---------------------------------------- + +TITLE: Renaming a tmux window with libtmux +DESCRIPTION: Shows how to rename the current tmux window using the `window.rename_window()` method. This updates the window's display name within tmux. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_18 + +LANGUAGE: python +CODE: +``` +window.rename_window('libtmuxower') +``` + +---------------------------------------- + +TITLE: Start tmux Server in Console +DESCRIPTION: Initiates a new tmux server instance in the console, typically run in a separate terminal to host sessions. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/context_managers.md#_snippet_0 + +LANGUAGE: console +CODE: +``` +$ tmux +``` + +---------------------------------------- + +TITLE: Accessing libtmux Pane Properties +DESCRIPTION: This section demonstrates how to get a `Pane` object from an active window and inspect its properties. It includes examples for `pane_current_command`, `pane_height`, `pane_width`, and `pane_index`, along with type checking. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/api/properties.md#_snippet_4 + +LANGUAGE: python +CODE: +``` +>>> pane = window.active_pane + +>>> pane +Pane(%1 Window(@1 ...:..., Session($1 libtmux_...))) +``` + +LANGUAGE: python +CODE: +``` +>>> pane.pane_current_command +'...' + +>>> type(pane.pane_current_command) + + +>>> pane.pane_height +'...' + +>>> pane.pane_width +'...' + +>>> pane.pane_index +'0' +``` + +---------------------------------------- + +TITLE: Assign a retrieved session to a variable +DESCRIPTION: Demonstrates the common pattern of renaming a session and then retrieving it by its new name to assign it to a variable for further manipulation. This establishes a working `Session` object for subsequent operations. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_12 + +LANGUAGE: python +CODE: +``` +server.sessions[0].rename_session('foo') +``` + +LANGUAGE: python +CODE: +``` +session = server.sessions.get(session_name="foo") +``` + +LANGUAGE: python +CODE: +``` +session +``` + +---------------------------------------- + +TITLE: Tagging and Releasing New Versions +DESCRIPTION: Steps for preparing a new release, including updating version information in `CHANGES` and `__init__.py`, committing changes with a specific message, and creating Git tags. These actions trigger CI/CD for deployment to PyPI. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/developing.md#_snippet_6 + +LANGUAGE: console +CODE: +``` +$ git commit -m 'Tag v0.9.1' +``` + +LANGUAGE: console +CODE: +``` +$ git tag v0.9.1 +``` + +LANGUAGE: console +CODE: +``` +$ git push +``` + +LANGUAGE: console +CODE: +``` +$ git push --tags +``` + +LANGUAGE: console +CODE: +``` +git commit -m 'build(libtmux): Tag v0.1.1' +``` + +LANGUAGE: console +CODE: +``` +git tag v0.1.1 +``` + +---------------------------------------- + +TITLE: Creating a new tmux window with libtmux +DESCRIPTION: Demonstrates how to create a new tmux window using `session.new_window()`. The `attach=False` argument creates the window in the background without switching to it. A custom `window_name` can be specified. The method returns the created `Window` object. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_13 + +LANGUAGE: python +CODE: +``` +session.new_window(attach=False, window_name="ha in the bg") +``` + +---------------------------------------- + +TITLE: Rename and retrieve sessions by name +DESCRIPTION: Shows how to rename a tmux session using `rename_session()` and subsequently retrieve it using `server.sessions.filter()` or `server.sessions.get()` with the new session name. This illustrates session management by name. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_11 + +LANGUAGE: python +CODE: +``` +server.sessions[0].rename_session('foo') +``` + +LANGUAGE: python +CODE: +``` +server.sessions.filter(session_name="foo")[0] +``` + +LANGUAGE: python +CODE: +``` +server.sessions.get(session_name="foo") +``` + +---------------------------------------- + +TITLE: Launch Python Interpreter +DESCRIPTION: Starts the Python interpreter in the console, enabling execution of Python code. Can be `python` or `ptpython`. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/context_managers.md#_snippet_1 + +LANGUAGE: console +CODE: +``` +$ python +``` + +---------------------------------------- + +TITLE: Running Project Tests +DESCRIPTION: Commands to execute the test suite using `pytest` via `uv` or `make`. Includes a helper command for basic test execution and a watch mode for continuous testing on file changes (requires `entr`). + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/developing.md#_snippet_1 + +LANGUAGE: console +CODE: +``` +$ uv run py.test +``` + +LANGUAGE: console +CODE: +``` +$ make test +``` + +LANGUAGE: console +CODE: +``` +$ make watch_test +``` + +---------------------------------------- + +TITLE: Start tmux session in console +DESCRIPTION: Initiates a new tmux server session in the console, providing the environment for libtmux interactions. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_0 + +LANGUAGE: console +CODE: +``` +tmux +``` + +---------------------------------------- + +TITLE: Formatting Code with Ruff Format +DESCRIPTION: Commands to automatically format Python code using `ruff format`. These can be run via `uv`, directly with `ruff format`, or through a `make` target. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/developing.md#_snippet_4 + +LANGUAGE: console +CODE: +``` +$ uv run ruff format . +``` + +LANGUAGE: console +CODE: +``` +$ ruff format . +``` + +LANGUAGE: console +CODE: +``` +$ make ruff_format +``` + +---------------------------------------- + +TITLE: Splitting a tmux window into a new pane with libtmux +DESCRIPTION: Explains how to split the current window into a new pane using `window.split()`. The `attach=False` argument prevents the cursor from switching to the newly created pane. The method returns the new `Pane` object. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_17 + +LANGUAGE: python +CODE: +``` +window.split(attach=False) +``` + +---------------------------------------- + +TITLE: Launch Python interpreter in console +DESCRIPTION: Starts the Python interpreter in the console, ready for interactive commands and libtmux script execution. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_1 + +LANGUAGE: console +CODE: +``` +python +``` + +---------------------------------------- + +TITLE: Filter sessions by ID +DESCRIPTION: Filters the list of sessions to find a specific session using its tmux ID (e.g., '$1') via `server.sessions.filter()`. This provides a reliable way to retrieve a session by its unique identifier. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_10 + +LANGUAGE: python +CODE: +``` +server.sessions.filter(session_id='$1')[0] +``` + +---------------------------------------- + +TITLE: Killing a tmux window by ID or name using libtmux +DESCRIPTION: Shows how to terminate a tmux window using `session.kill_window()`. This method accepts either the window's ID (e.g., `@2`) or its name as a target. It's equivalent to the `tmux kill-window -t` command. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_14 + +LANGUAGE: python +CODE: +``` +session.kill_window(window.window_id) +``` + +LANGUAGE: python +CODE: +``` +session.kill_window('ha in the bg') +``` + +---------------------------------------- + +TITLE: Moving cursor across tmux windows and panes with libtmux +DESCRIPTION: Illustrates how to control cursor movement when creating new panes or explicitly selecting existing ones. Omitting `attach=False` in `window.split()` moves the cursor, or `pane.select()` can be used for explicit selection. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_19 + +LANGUAGE: python +CODE: +``` +pane = window.split() +``` + +LANGUAGE: python +CODE: +``` +pane = window.split(attach=False) +``` + +LANGUAGE: python +CODE: +``` +pane.select() +``` + +---------------------------------------- + +TITLE: Get all tmux windows from libtmux Server +DESCRIPTION: Retrieves a list of all tmux windows across all sessions managed by the libtmux server object. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_5 + +LANGUAGE: python +CODE: +``` +server.windows +``` + +---------------------------------------- + +TITLE: Get all tmux panes from libtmux Server +DESCRIPTION: Retrieves a list of all tmux panes across all windows managed by the libtmux server object. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_6 + +LANGUAGE: python +CODE: +``` +server.panes +``` + +---------------------------------------- + +TITLE: Sending commands to tmux panes remotely with libtmux +DESCRIPTION: Details how to send keyboard inputs and commands to a tmux pane using `pane.send_keys()`. It covers sending keys without pressing Enter (`enter=False`), explicitly pressing Enter (`pane.enter()`), and suppressing commands from shell history (`suppress_history=True`). + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/quickstart.md#_snippet_20 + +LANGUAGE: python +CODE: +``` +window = session.new_window(attach=False, window_name="test") +pane = window.split(attach=False) +pane.send_keys('echo hey', enter=False) +``` + +LANGUAGE: python +CODE: +``` +pane.enter() +``` + +LANGUAGE: python +CODE: +``` +pane.send_keys('echo Howdy', enter=True, suppress_history=True) +``` + +---------------------------------------- + +TITLE: Get windows within a tmux session +DESCRIPTION: Retrieves a list of all windows belonging to a specific libtmux session object, enabling navigation within that session. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_8 + +LANGUAGE: python +CODE: +``` +session.windows +``` + +---------------------------------------- + +TITLE: Linting and Fixing Code with Ruff +DESCRIPTION: Commands to perform code linting and automatic fixes using the `ruff` tool. This includes execution via `uv`, direct `ruff` commands, `make` targets, and a watch mode for continuous linting (requires `entr`). + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/developing.md#_snippet_3 + +LANGUAGE: console +CODE: +``` +$ uv run ruff +``` + +LANGUAGE: console +CODE: +``` +$ ruff check . +``` + +LANGUAGE: console +CODE: +``` +$ make ruff +``` + +LANGUAGE: console +CODE: +``` +$ make watch_ruff +``` + +LANGUAGE: console +CODE: +``` +$ uv run ruff check . --fix +``` + +LANGUAGE: console +CODE: +``` +$ ruff check . --fix +``` + +---------------------------------------- + +TITLE: Create a New tmux Session via Console +DESCRIPTION: Demonstrates how to create a new tmux session directly from the terminal using the `tmux` command-line utility. This example sets the session name to 'foo' and the initial window name to 'bar'. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_1 + +LANGUAGE: console +CODE: +``` +tmux new-session -s foo -n bar +``` + +---------------------------------------- + +TITLE: Performing Static Type Checks with Mypy +DESCRIPTION: Commands to run static type analysis on the project using `mypy`. Options include running via `uv`, direct `mypy` commands, `make` targets, and a watch mode for continuous type checking (requires `entr`). + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/developing.md#_snippet_5 + +LANGUAGE: console +CODE: +``` +$ uv run mypy . +``` + +LANGUAGE: console +CODE: +``` +$ mypy . +``` + +LANGUAGE: console +CODE: +``` +$ make mypy +``` + +LANGUAGE: console +CODE: +``` +$ make watch_mypy +``` + +---------------------------------------- + +TITLE: Get panes within a tmux window +DESCRIPTION: Retrieves a list of all panes belonging to a specific libtmux window object, enabling navigation within that window. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_12 + +LANGUAGE: python +CODE: +``` +window.panes +``` + +---------------------------------------- + +TITLE: Get active pane in a tmux window +DESCRIPTION: Retrieves the currently active pane within a specific libtmux window object, indicating the current focus. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_13 + +LANGUAGE: python +CODE: +``` +window.active_pane +``` + +---------------------------------------- + +TITLE: Get all tmux sessions from libtmux Server +DESCRIPTION: Retrieves a list of all active tmux sessions managed by the libtmux server object, allowing iteration and access to individual sessions. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_4 + +LANGUAGE: python +CODE: +``` +server.sessions +``` + +---------------------------------------- + +TITLE: Get active window and pane in a tmux session +DESCRIPTION: Retrieves the currently active window and pane within a specific libtmux session object, useful for understanding the current focus. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_9 + +LANGUAGE: python +CODE: +``` +session.active_window + +>>> session.active_pane +``` + +---------------------------------------- + +TITLE: Get specific tmux pane by ID +DESCRIPTION: Retrieves a specific pane from a window's panes collection using its unique 'pane_id', allowing direct access to a pane. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_16 + +LANGUAGE: python +CODE: +``` +window.panes.get(pane_id=pane.pane_id) +``` + +---------------------------------------- + +TITLE: Create and manage temporary tmux servers in pytest +DESCRIPTION: The `TestServer` fixture provides a factory for creating independent, temporary tmux server instances with unique socket names. This allows testing scenarios involving multiple servers or custom configurations, ensuring automatic cleanup after tests. The second example shows how to use it with a custom configuration file. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/pytest-plugin/index.md#_snippet_2 + +LANGUAGE: python +CODE: +``` +def test_something(TestServer): + Server = TestServer() # Get unique partial'd Server + server = Server() # Create server instance + + session = server.new_session() + assert server.is_alive() +``` + +LANGUAGE: python +CODE: +``` +def test_with_config(TestServer, tmp_path): + config_file = tmp_path / "tmux.conf" + config_file.write_text("set -g status off") + + Server = TestServer() + server = Server(config_file=str(config_file)) +``` + +---------------------------------------- + +TITLE: Connecting to a libtmux Server +DESCRIPTION: This snippet shows how to establish a connection to the default tmux server using `libtmux.Server()`. It initializes a Server object, which then allows interaction with tmux sessions, windows, and panes. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/api/properties.md#_snippet_1 + +LANGUAGE: python +CODE: +``` +>>> import libtmux +>>> t = libtmux.Server() +>>> t +Server(socket_path=/tmp/tmux-.../default) +``` + +---------------------------------------- + +TITLE: libtmux.Session Class API Reference +DESCRIPTION: Comprehensive API documentation for the `libtmux.Session` class, which represents a tmux session. This class manages windows and panes, and provides methods for interacting with a tmux session programmatically. It exists within a `libtmux.Server` instance and is identified by a '$' prefix. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/api/sessions.md#_snippet_0 + +LANGUAGE: APIDOC +CODE: +``` +libtmux.Session Class: + Represents a tmux session, a fundamental unit within the tmux terminal multiplexer. + + Inheritance: + - Inherits from `libtmux.common.TMUX` (implied by context and typical libtmux structure) + + Attributes: + - id (str): The unique identifier for the session, typically prefixed with '$' (e.g., '$313'). + - server (libtmux.Server): A reference to the parent `libtmux.Server` instance that contains this session. + - windows (list[libtmux.Window]): A list of `libtmux.Window` objects currently open within this session. + - name (str): The name of the session. + + Methods (common examples, full list generated by autoclass): + - attach(): Attaches the current terminal to this tmux session. + - kill_session(): Terminates and removes this tmux session. + - new_window(attach: bool = True, window_name: str = None, start_directory: str = None) -> libtmux.Window: + Creates a new window within this session. + - attach (bool): If True, attach to the new window immediately. + - window_name (str): Optional name for the new window. + - start_directory (str): Optional starting directory for the new window. + - Returns: The newly created `libtmux.Window` object. + - find_where(attribute: str, value: str) -> Union[libtmux.Window, libtmux.Pane, None]: + Finds a window or pane within the session based on an attribute and its value. + - select_window(target_window: Union[str, int, libtmux.Window]): + Selects a specific window within the session by name, index, or object. + - rename_session(new_name: str): + Renames the current session to `new_name`. + - list_windows() -> list[libtmux.Window]: + Returns a list of all `libtmux.Window` objects in the session. + - find_window(target_window: Union[str, int]) -> Union[libtmux.Window, None]: + Finds a window by name or index within the session. + - attached_window() -> libtmux.Window: + Returns the currently attached window in the session. + - attached_pane() -> libtmux.Pane: + Returns the currently attached pane in the session. +``` + +---------------------------------------- + +TITLE: Split tmux Windows and Create Panes with libtmux +DESCRIPTION: Illustrates how to split a tmux window into new panes and create entirely new windows using `libtmux`. It covers creating panes both attached and detached, selecting panes, and initializing new windows with specific names. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_15 + +LANGUAGE: python +CODE: +``` +>>> window = session.active_window +>>> window.split(attach=False) +Pane(%2 Window(@1 1:... Session($1 ...))) +>>> pane = window.split() +>>> pane = window.split(attach=False) +>>> pane.select() +Pane(%3 Window(@1 1:..., Session($1 ...))) +>>> window = session.new_window(attach=False, window_name="test") +>>> window +Window(@2 2:test, Session($1 ...)) +>>> pane = window.split(attach=False) +>>> pane +Pane(%5 Window(@2 2:test, Session($1 ...))) +``` + +---------------------------------------- + +TITLE: libtmux Server Context Manager Usage +DESCRIPTION: Demonstrates using `libtmux.Server()` as a context manager. A temporary tmux server is created and automatically killed upon exiting the `with` block, ensuring resource cleanup. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/context_managers.md#_snippet_3 + +LANGUAGE: python +CODE: +``` +with Server() as server: + session = server.new_session() + print(server.is_alive()) +True +print(server.is_alive()) +False +``` + +---------------------------------------- + +TITLE: Connect to tmux Server using libtmux in Python +DESCRIPTION: Illustrates how to import the `libtmux` library and establish a connection to the default tmux server. The `Server()` object represents the active tmux server instance, allowing for subsequent programmatic control. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_4 + +LANGUAGE: python +CODE: +``` +import libtmux +svr = libtmux.Server() +svr +``` + +---------------------------------------- + +TITLE: Split Window and Create Pane via libtmux Command +DESCRIPTION: Demonstrates how to split an existing tmux window and create a new pane using the `window.cmd()` method in `libtmux`. This command returns the ID of the newly created pane, which can then be used to interact with it programmatically. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_8 + +LANGUAGE: python +CODE: +``` +window.cmd('split-window', '-P', '-F#{pane_id}').stdout[0] +``` + +---------------------------------------- + +TITLE: Instantiate libtmux Window Object from ID +DESCRIPTION: Explains how to construct a `Window` object in `libtmux` directly from its window ID. This method is crucial for obtaining a rich, interactive object representation from raw command output, allowing for detailed control over specific windows. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_7 + +LANGUAGE: python +CODE: +``` +Window.from_window_id(window_id=session.cmd('new-window', '-P', '-F#{window_id}').stdout[0], server=session.server) +``` + +---------------------------------------- + +TITLE: libtmux Relational Object Model +DESCRIPTION: This documentation outlines the hierarchical relationships between the core `libtmux` objects: `Server`, `Session`, `Window`, and `Pane`. It illustrates how these objects are connected, defining their parent-child dependencies within the `libtmux` abstraction. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/about.md#_snippet_0 + +LANGUAGE: APIDOC +CODE: +``` +Object | Child | Parent +---------------- | ---------------- | ---------------- +{class}`Server` | {class}`Session` | None +{class}`Session` | {class}`Window` | {class}`Server` +{class}`Window` | {class}`Pane` | {class}`Session` +{class}`Pane` | None | {class}`Window` +``` + +---------------------------------------- + +TITLE: Execute Raw tmux Commands with libtmux Server +DESCRIPTION: Demonstrates how to execute arbitrary tmux commands using the `server.cmd()` method in `libtmux`. This method allows direct interaction with the tmux server, respecting the configured socket name, and can be used to display messages or create new sessions. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_5 + +LANGUAGE: python +CODE: +``` +server = Server(socket_name='libtmux_doctest') +server.cmd('display-message', 'hello world') +server.cmd('new-session', '-d', '-P', '-F#{session_id}').stdout[0] +``` + +---------------------------------------- + +TITLE: Import libtmux Library +DESCRIPTION: Imports the `libtmux` library into a Python environment, making its functionalities available for use. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/context_managers.md#_snippet_2 + +LANGUAGE: python +CODE: +``` +import libtmux +``` + +---------------------------------------- + +TITLE: Send Keystrokes to tmux Panes with libtmux +DESCRIPTION: Explains how to send keyboard inputs to a tmux pane using `pane.send_keys()`. It covers sending a complete command with an implicit Enter, and sending parts of a command followed by an explicit `pane.enter()` call. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_16 + +LANGUAGE: python +CODE: +``` +>>> pane.send_keys('echo hey send now') + +>>> pane.send_keys('echo hey', enter=False) +>>> pane.enter() +Pane(%1 ...) +``` + +---------------------------------------- + +TITLE: libtmux Window Context Manager Usage +DESCRIPTION: Shows how to use `session.new_window()` as a context manager. A temporary tmux window is created and automatically closed upon exiting the `with` block. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/context_managers.md#_snippet_5 + +LANGUAGE: python +CODE: +``` +server = Server() +session = server.new_session() +with session.new_window() as window: + print(window in session.windows) + pane = window.split() +True +print(window in session.windows) +False +``` + +---------------------------------------- + +TITLE: Dynamically Activate Sidebar Navigation Links +DESCRIPTION: This JavaScript snippet identifies sidebar navigation links that point to the current hostname. If a link is not already marked as 'active', it replaces the anchor tag with a `` element, applying an 'active' class to visually indicate the current page without altering the URL. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/_templates/sidebar/projects.html#_snippet_0 + +LANGUAGE: javascript +CODE: +``` +(() => { + const sidebar = document.getElementById("sidebar-projects"); + sidebar.querySelectorAll(`a[href*="${window.location.hostname}"]`) + .forEach((link) => { + if (!link.classList.contains("active")) { + const d = document.createElement('span'); + d.innerHTML = link.innerHTML; + d.classList.add("active"); + link.parentNode.replaceChild(d, link); + } + }); +})() +``` + +---------------------------------------- + +TITLE: Create New Window via Session Command in libtmux +DESCRIPTION: Shows how to create a new window within an existing tmux session using the `session.cmd()` method. This command returns the ID of the newly created window in a formatted string, enabling further programmatic manipulation. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_6 + +LANGUAGE: python +CODE: +``` +session.cmd('new-window', '-P').stdout[0] +``` + +---------------------------------------- + +TITLE: Instantiate libtmux Pane Object from ID +DESCRIPTION: Illustrates how to create a `Pane` object in `libtmux` directly from its pane ID. This allows for programmatic interaction with a specific pane based on its identifier, providing a structured way to manage pane properties and content. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_9 + +LANGUAGE: python +CODE: +``` +Pane.from_pane_id(pane_id=window.cmd('split-window', '-P', '-F#{pane_id}').stdout[0], server=window.server) +``` + +---------------------------------------- + +TITLE: libtmux Session Context Manager Usage +DESCRIPTION: Illustrates using `server.new_session()` as a context manager. A temporary tmux session is created and automatically killed when the `with` block is exited, ensuring proper cleanup. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/context_managers.md#_snippet_4 + +LANGUAGE: python +CODE: +``` +server = Server() +with server.new_session() as session: + print(session in server.sessions) + window = session.new_window() +True +print(session in server.sessions) +False +``` + +---------------------------------------- + +TITLE: libtmux Pane Context Manager Usage +DESCRIPTION: Demonstrates using `window.split()` as a context manager for a tmux pane. The pane is automatically killed and removed when the `with` block is exited. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/context_managers.md#_snippet_6 + +LANGUAGE: python +CODE: +``` +server = Server() +session = server.new_session() +window = session.new_window() +with window.split() as pane: + print(pane in window.panes) + pane.send_keys('echo "Hello"') +True +print(pane in window.panes) +False +``` + +---------------------------------------- + +TITLE: Create New Background Window in libtmux Session +DESCRIPTION: Illustrates how to create a new tmux window within a session without immediately attaching to it, using `session.new_window(attach=False)`. It also shows how to search for and retrieve this newly created window using filtering methods. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_12 + +LANGUAGE: python +CODE: +``` +bg_window = session.new_window(attach=False, window_name="ha in the bg") +bg_window +session.windows.filter(window_name__startswith="ha") +session.windows.get(window_name__startswith="ha") +``` + +---------------------------------------- + +TITLE: Rename tmux Windows using libtmux +DESCRIPTION: Shows how to rename an existing tmux window programmatically using the `rename_window()` method of a window object in `libtmux`. This allows for dynamic naming of windows. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_14 + +LANGUAGE: python +CODE: +``` +>>> window.rename_window('libtmuxower') +Window(@1 1:libtmuxower, Session($1 ...)) +``` + +---------------------------------------- + +TITLE: Accessing libtmux Window Properties +DESCRIPTION: This snippet illustrates how to obtain a `Window` object from an active session and access its fundamental properties. It covers retrieving `window_name`, `window_id`, `window_height`, `window_width`, and `window_panes`. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/api/properties.md#_snippet_3 + +LANGUAGE: python +CODE: +``` +>>> window = session.active_window + +>>> window +Window(@1 ...:..., Session($1 ...)) +``` + +LANGUAGE: python +CODE: +``` +>>> window.window_name +'...' + +>>> window.window_id +'@1' + +>>> window.window_height +'...' + +>>> window.window_width +'...' +``` + +LANGUAGE: python +CODE: +``` +>>> window.window_panes +'1' +``` + +---------------------------------------- + +TITLE: Close tmux Windows using libtmux +DESCRIPTION: Demonstrates how to programmatically close or kill tmux windows using the `libtmux` Python library. This involves calling the `kill()` method on a window object to terminate it. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_13 + +LANGUAGE: python +CODE: +``` +>>> bg_window.kill() +>>> w = session.active_window +>>> w.kill() +``` + +---------------------------------------- + +TITLE: List and Filter tmux Sessions using libtmux +DESCRIPTION: Shows how to retrieve a list of all active tmux sessions via `server.sessions`. It also demonstrates filtering sessions by attributes like `history_limit` and performing direct lookups by `session_id` or `session_name` for precise session management. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_10 + +LANGUAGE: python +CODE: +``` +server.sessions +server.sessions.filter(history_limit='2000') +server.sessions.get(session_id="$1") +server.sessions[0].rename_session('foo') +server.sessions.filter(session_name="foo") +server.sessions.get(session_name="foo") +``` + +---------------------------------------- + +TITLE: libtmux.Pane Class API Documentation Directive +DESCRIPTION: This reStructuredText directive specifies the generation of comprehensive API documentation for the `libtmux.Pane` Python class. It instructs Sphinx to include all public, private, and inherited members, along with the class's inheritance hierarchy, ordered by source. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/api/panes.md#_snippet_0 + +LANGUAGE: APIDOC +CODE: +``` +.. autoclass:: libtmux.Pane + :members: + :inherited-members: + :private-members: + :show-inheritance: + :member-order: bysource +``` + +---------------------------------------- + +TITLE: tmux Object Identifiers and Lookup +DESCRIPTION: This section details the unique identifiers used by tmux for its various objects (Session, Window, Pane) and how `libtmux` utilizes these IDs for lookup and management. It also clarifies the distinction between unique IDs and positional indices within tmux. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/about.md#_snippet_1 + +LANGUAGE: APIDOC +CODE: +``` +Object | Prefix | Example +---------------- | ------ | ----------------------------------------- +{class}`Server` | N/A | N/A, uses `socket-name` and `socket-path` +{class}`Session` | `$` | `$13` +{class}`Window` | `@` | `@3243` +{class}`Pane` | `%` | `%5433` + +Tmux has unique IDs for sessions, windows and panes. +panes use `%`, such as `%1234` +windows use `@`, such as `@2345` +sessions use `$`, such as `$13` + +Tmux provides `window_id` as a unique identifier. + +What is a {pane,window}_index vs a {pane,window,session}_id? +Pane index refers to the order of a pane on the screen. +Window index refers to the number of the window in the session. +To assert pane, window and session data, libtmux will use +{meth}`Server.sessions()`, {meth}`Session.windows()`, +{meth}`Window.panes()` to update objects. +``` + +---------------------------------------- + +TITLE: Traverse tmux Objects in libtmux +DESCRIPTION: Shows how to navigate the object hierarchy within `libtmux`, specifically accessing the parent window from a pane object and the parent session from a window object. This is useful for contextual operations. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_18 + +LANGUAGE: python +CODE: +``` +>>> pane.window +Window(@1 1:..., Session($1 ...)) +>>> pane.window.session +Session($1 ...) +``` + +---------------------------------------- + +TITLE: Capture Output from tmux Panes using libtmux +DESCRIPTION: Demonstrates how to clear a tmux pane and then capture its output after executing a command. This involves using `pane.clear()` to reset the pane and `pane.cmd('capture-pane', '-p').stdout` to retrieve the pane's content. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_17 + +LANGUAGE: python +CODE: +``` +>>> pane.clear() # clear the pane +Pane(%1 ...) +>>> pane.send_keys("cowsay 'hello'", enter=True) +>>> print('\n'.join(pane.cmd('capture-pane', '-p').stdout)) # doctest: +SKIP +$ cowsay 'hello' + _______ +< hello > + ------- + \ ^__^ + \ (oo)\_______ + (__)\ )\/\ + ||----w | + || || +... +``` + +---------------------------------------- + +TITLE: Accessing libtmux Session Properties +DESCRIPTION: This section demonstrates how to retrieve a `Session` object and access its basic attributes like `session_name` and `session_id`. It also shows how to inspect all available attributes using `Obj.__dataclass_fields__.keys()` and access `session_windows`. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/api/properties.md#_snippet_2 + +LANGUAGE: python +CODE: +``` +>>> session = server.sessions[0] +>>> session +Session($1 libtmux_...) +``` + +LANGUAGE: python +CODE: +``` +>>> session.session_name +'libtmux_...' + +>>> session.session_id +'$1' +``` + +LANGUAGE: python +CODE: +``` +from libtmux.neo import Obj + +>>> sorted(list(Obj.__dataclass_fields__.keys())) +['session_attached', 'session_created', ...] +``` + +LANGUAGE: python +CODE: +``` +>>> session.session_windows +'...' +``` + +---------------------------------------- + +TITLE: Control and Rename tmux Sessions using libtmux +DESCRIPTION: Demonstrates how to interact with a `Session` object in `libtmux`, specifically showing how to rename an existing tmux session programmatically. This allows for dynamic adjustment of session identifiers. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/README.md#_snippet_11 + +LANGUAGE: python +CODE: +``` +session +session.rename_session('my-session') +``` + +---------------------------------------- + +TITLE: Set a temporary home directory for pytest tests +DESCRIPTION: This pytest fixture demonstrates how to temporarily set the `HOME` environment variable to a test-specific path. This is useful for isolating tests that rely on user-specific configuration files, such as `.tmux.conf`, ensuring a clean state for each test run by using `monkeypatch`. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/pytest-plugin/index.md#_snippet_3 + +LANGUAGE: python +CODE: +``` +import pathlib +import pytest + +@pytest.fixture(autouse=True, scope="function") +def set_home( + monkeypatch: pytest.MonkeyPatch, + user_path: pathlib.Path, +): + monkeypatch.setenv("HOME", str(user_path)) +``` + +---------------------------------------- + +TITLE: Access and inspect first tmux session +DESCRIPTION: Accesses the first session from the list of server sessions and displays its object representation, demonstrating how to select a specific session. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_7 + +LANGUAGE: python +CODE: +``` +session = server.sessions[0] +>>> session +``` + +---------------------------------------- + +TITLE: Access and inspect tmux window properties +DESCRIPTION: Accesses the first window from a session and displays its 'window_index' property, illustrating how to retrieve window-specific attributes. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_10 + +LANGUAGE: python +CODE: +``` +window = session.windows[0] +>>> window.window_index +``` + +---------------------------------------- + +TITLE: Traverse up hierarchy from tmux pane +DESCRIPTION: Accesses the first pane from a window and demonstrates traversing up the object hierarchy to its parent window, session, and server, verifying their IDs and relationships. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_14 + +LANGUAGE: python +CODE: +``` +pane = window.panes[0] +>>> pane.window.window_id == window.window_id +True +>>> pane.session.session_id == session.session_id +True +>>> pane.server is server +True +``` + +---------------------------------------- + +TITLE: Nested libtmux Context Managers for Cleanup +DESCRIPTION: Showcases nesting `libtmux` context managers (server, session, window, pane) for hierarchical cleanup. All tmux objects are automatically cleaned up in reverse order upon exiting the outermost `with` block. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/context_managers.md#_snippet_7 + +LANGUAGE: python +CODE: +``` +with Server() as server: + with server.new_session() as session: + with session.new_window() as window: + with window.split() as pane: + pane.send_keys('echo "Hello"') + # Do work with the pane + # Everything is cleaned up automatically when exiting contexts +``` + +---------------------------------------- + +TITLE: Inspect libtmux Server object +DESCRIPTION: Displays the representation of the libtmux server object, showing its current state and properties, such as the socket name. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_3 + +LANGUAGE: python +CODE: +``` +server +``` + +---------------------------------------- + +TITLE: Create new tmux session with libtmux +DESCRIPTION: Creates a new tmux session programmatically using the libtmux server object. This establishes a test session for further operations and object traversal. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_2 + +LANGUAGE: python +CODE: +``` +session = server.new_session() +``` + +---------------------------------------- + +TITLE: Customize tmux session parameters in pytest +DESCRIPTION: This Python fixture demonstrates how to override default session parameters for a tmux session created by the libtmux pytest plugin. It sets the session's initial dimensions (x and y) which are then passed to `Server.new_session` when a new session is created. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/pytest-plugin/index.md#_snippet_1 + +LANGUAGE: python +CODE: +``` +import pytest + +@pytest.fixture +def session_params(): + return { + 'x': 800, + 'y': 600 + } + + +def test_something(session): + assert session +``` + +---------------------------------------- + +TITLE: Filter tmux windows by index +DESCRIPTION: Filters the list of windows within a session to find specific windows based on their 'window_index' property, demonstrating object filtering capabilities. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_15 + +LANGUAGE: python +CODE: +``` +session.windows.filter(window_index=window.window_index) +``` + +---------------------------------------- + +TITLE: Check object relationships in libtmux hierarchy +DESCRIPTION: Verifies if a window is part of a session's windows, a pane is part of a window's panes, and a session is part of the server's sessions, confirming hierarchical integrity. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_17 + +LANGUAGE: python +CODE: +``` +window in session.windows +True +>>> pane in window.panes +True +>>> session in server.sessions +True +``` + +---------------------------------------- + +TITLE: Access parent session from tmux window +DESCRIPTION: Retrieves the parent session object from a libtmux window and verifies its ID matches the original session, demonstrating upward traversal. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_11 + +LANGUAGE: python +CODE: +``` +window.session +>>> window.session.session_id == session.session_id +``` + +---------------------------------------- + +TITLE: Check if tmux window is active +DESCRIPTION: Compares a window's ID with the active window's ID in the current session to determine if it is the active window. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_18 + +LANGUAGE: python +CODE: +``` +window.window_id == session.active_window.window_id +``` + +---------------------------------------- + +TITLE: Check if tmux pane is active +DESCRIPTION: Compares a pane's ID with the active pane's ID in the current window to determine if it is the active pane. + +SOURCE: https://github.com/tmux-python/libtmux/blob/master/docs/topics/traversal.md#_snippet_19 + +LANGUAGE: python +CODE: +``` +pane.pane_id == window.active_pane.pane_id +``` \ No newline at end of file diff --git a/aiprompts/psutil_python.md b/aiprompts/psutil_python.md new file mode 100644 index 0000000..4ea850b --- /dev/null +++ b/aiprompts/psutil_python.md @@ -0,0 +1,14342 @@ +======================== +CODE SNIPPETS +======================== +TITLE: psutil Development Setup and Testing +DESCRIPTION: Commands for cloning the psutil repository, installing dependencies, building, installing, and running tests. Includes options for parallel testing, memory leak testing, coverage, and linting. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/DEVGUIDE.rst#_snippet_0 + +LANGUAGE: bash +CODE: +``` +git clone git@github.com:giampaolo/psutil.git +make install-sysdeps # install gcc and python headers +make install-pydeps-test # install python deps necessary to run unit tests +make build +make install +make test +``` + +LANGUAGE: bash +CODE: +``` +python3 -m psutil.tests +``` + +LANGUAGE: bash +CODE: +``` +make clean # remove build files +make install-pydeps-dev # install dev deps (ruff, black, ...) +make test # run tests +make test-parallel # run tests in parallel (faster) +make test-memleaks # run memory leak tests +make test-coverage # run test coverage +make lint-all # run linters +make fix-all # fix linters errors +make uninstall +make help +``` + +LANGUAGE: bash +CODE: +``` +make test ARGS=psutil/tests/test_system.py::TestDiskAPIs::test_disk_usage +``` + +LANGUAGE: bash +CODE: +``` +make test ARGS=test_script.py # on UNIX +make test test_script.py # on Windows +``` + +LANGUAGE: bash +CODE: +``` +make test PYTHON=python3.5 # UNIX +make test -p C:\python35\python.exe # Windows +``` + +---------------------------------------- + +TITLE: Install psutil on macOS (Source) +DESCRIPTION: On macOS, install Xcode command-line tools first, then use pip to install psutil from source. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_8 + +LANGUAGE: bash +CODE: +``` +xcode-select --install +pip install --no-binary :all: psutil +``` + +---------------------------------------- + +TITLE: Install psutil on Windows (Source) +DESCRIPTION: To build psutil from source on Windows, you must have Visual Studio 2017 or later installed. MinGW is not supported. After installation, use pip to install psutil. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_7 + +LANGUAGE: bash +CODE: +``` +pip install --no-binary :all: psutil +``` + +---------------------------------------- + +TITLE: Install psutil on FreeBSD (Source) +DESCRIPTION: On FreeBSD, install the Python 3 package and GCC using pkg, then install psutil using pip. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_9 + +LANGUAGE: bash +CODE: +``` +pkg install python3 gcc +python3 -m pip install psutil +``` + +---------------------------------------- + +TITLE: Install psutil from Source (PyPI) +DESCRIPTION: This command fetches the latest source distribution from PyPI and installs it, forcing a build from source even if wheels are available. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_2 + +LANGUAGE: bash +CODE: +``` +pip install --no-binary :all: psutil +``` + +---------------------------------------- + +TITLE: Install psutil system-wide with sudo +DESCRIPTION: To install psutil system-wide on UNIX-like systems and avoid permission errors, prepend the pip install command with 'sudo'. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_17 + +LANGUAGE: bash +CODE: +``` +sudo pip install psutil +``` + +---------------------------------------- + +TITLE: Install psutil on OpenBSD (Source) +DESCRIPTION: On OpenBSD, set the PKG_PATH environment variable to the appropriate mirror, install Python 3 and GCC using pkg_add, and then install psutil. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_10 + +LANGUAGE: bash +CODE: +``` +export PKG_PATH=https://cdn.openbsd.org/pub/OpenBSD/`uname -r`/packages/`uname -m`/ +pkg_add -v python3 gcc +pip install psutil +``` + +---------------------------------------- + +TITLE: Install psutil on NetBSD (Source) +DESCRIPTION: On NetBSD, set the PKG_PATH for packages, install the pkgin package manager, and then install Python 3.11 and its dependencies along with psutil. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_11 + +LANGUAGE: bash +CODE: +``` +export PKG_PATH="https://ftp.netbsd.org/pub/pkgsrc/packages/NetBSD/`uname -m`/`uname -r`/All" +pkgin install python311-* gcc12-* py311-setuptools-* py311-pip-* +python3.11 -m pip install psutil +``` + +---------------------------------------- + +TITLE: Install psutil from Source (UNIX) +DESCRIPTION: For UNIX systems, you can compile psutil from source. This involves installing system dependencies first, then building and installing the package. It's recommended to use the provided Makefile targets. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_1 + +LANGUAGE: bash +CODE: +``` +make install-sysdeps +make build +make install +``` + +---------------------------------------- + +TITLE: Install pip using wget +DESCRIPTION: If pip is not installed, you can download the get-pip.py script using wget and execute it with Python 3. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_13 + +LANGUAGE: bash +CODE: +``` +wget https://bootstrap.pypa.io/get-pip.py -O - | python3 +``` + +---------------------------------------- + +TITLE: psutil Documentation Build +DESCRIPTION: Commands to build the documentation for psutil, requiring development dependencies to be installed first, then navigating to the docs directory and running the make command. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/DEVGUIDE.rst#_snippet_3 + +LANGUAGE: bash +CODE: +``` +make install-pydeps-dev; cd docs; make html +``` + +---------------------------------------- + +TITLE: Install psutil on Arch Linux (Source) +DESCRIPTION: For Arch Linux, ensure you have the necessary build tools like 'cmake', 'gcc', and 'python' installed before proceeding with the psutil installation from source. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_5 + +LANGUAGE: bash +CODE: +``` +sudo pacman -S cmake gcc python +pip install --no-binary :all: psutil +``` + +---------------------------------------- + +TITLE: Install pip on Windows +DESCRIPTION: On Windows, download the get-pip.py script, open cmd.exe, and run the script using the 'py' command. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_15 + +LANGUAGE: bash +CODE: +``` +py get-pip.py +``` + +---------------------------------------- + +TITLE: Install psutil on Debian/Ubuntu (Source) +DESCRIPTION: On Debian-based systems like Ubuntu, you need to install the GCC compiler and Python development headers before installing psutil from source. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_3 + +LANGUAGE: bash +CODE: +``` +sudo apt-get install gcc python3-dev +pip install --no-binary :all: psutil +``` + +---------------------------------------- + +TITLE: Install psutil using pip (Wheels) +DESCRIPTION: The simplest way to install psutil is using pip, which will automatically use pre-compiled wheels if available for your platform and architecture. This method does not require a C compiler. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_0 + +LANGUAGE: python +CODE: +``` +pip install psutil +``` + +---------------------------------------- + +TITLE: Install psutil on RedHat/CentOS (Source) +DESCRIPTION: On RedHat-based systems like CentOS, install the GCC compiler and Python development headers (python3-devel) before building psutil from source. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_4 + +LANGUAGE: bash +CODE: +``` +sudo yum install gcc python3-devel +pip install --no-binary :all: psutil +``` + +---------------------------------------- + +TITLE: Install psutil on Sun Solaris (Source) +DESCRIPTION: On Sun Solaris, if the 'cc' compiler is not installed, create a symbolic link to 'gcc'. Then, install GCC using pkg and install psutil using pip. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_12 + +LANGUAGE: bash +CODE: +``` +sudo ln -s /usr/bin/gcc /usr/local/bin/cc +pkg install gcc +pip install psutil +``` + +---------------------------------------- + +TITLE: Install psutil +DESCRIPTION: Instructions for installing the psutil library using pip. For other platforms, refer to the INSTALL.rst file for detailed instructions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_1 + +LANGUAGE: bash +CODE: +``` +pip install psutil +``` + +---------------------------------------- + +TITLE: Install pip using curl +DESCRIPTION: Alternatively, you can use curl to download and execute the get-pip.py script with Python 3. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_14 + +LANGUAGE: bash +CODE: +``` +python3 < <(curl -s https://bootstrap.pypa.io/get-pip.py) +``` + +---------------------------------------- + +TITLE: Getting Windows Service Information +DESCRIPTION: Demonstrates how to retrieve detailed information about a specific Windows service by its name. This includes binary path, description, start type, and status. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_39 + +LANGUAGE: python +CODE: +``` +s = psutil.win_service_get('alg') +s.as_dict() +``` + +---------------------------------------- + +TITLE: Install psutil on Alpine Linux (Source) +DESCRIPTION: On Alpine Linux, you need to install GCC, Python 3 development files, musl development headers, and Linux kernel headers to compile psutil from source. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_6 + +LANGUAGE: bash +CODE: +``` +sudo apk add gcc python3-dev musl-dev linux-headers +pip install --no-binary :all: psutil +``` + +---------------------------------------- + +TITLE: Install psutil when pip is not in PATH +DESCRIPTION: If the 'pip' command is not found, you can often invoke it as a module of your Python 3 installation. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/INSTALL.rst#_snippet_16 + +LANGUAGE: bash +CODE: +``` +python3 -m pip install psutil +``` + +---------------------------------------- + +TITLE: psutil Project Navigation and Links +DESCRIPTION: This section provides a central hub for navigating the psutil project, including links to the home page, installation instructions, documentation, download page, community forum, blog, funding information, and changelog. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_1 + +LANGUAGE: html +CODE: +``` +
+ +
+
+ Home    + Install    + Documentation    + Download    + Forum    + Blog    + Funding    + What's new    +
+``` + +---------------------------------------- + +TITLE: Memory Usage Example +DESCRIPTION: Demonstrates how to access and interpret virtual memory information using psutil. It shows how to get memory statistics and check if available memory is below a certain threshold. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_14 + +LANGUAGE: python +CODE: +``` +import psutil + +mem = psutil.virtual_memory() + +# Check if available memory is less than 100MB +THRESHOLD = 100 * 1024 * 1024 # 100MB +if mem.available <= THRESHOLD: + print("Warning: Low available memory!") + +print(f"Total memory: {mem.total}") +print(f"Available memory: {mem.available}") +print(f"Memory usage percentage: {mem.percent}%") +``` + +---------------------------------------- + +TITLE: psutil Development Guide Link +DESCRIPTION: Provides a direct link to the psutil Development Guide, which helps contributors familiarize themselves with the codebase and tooling. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/CONTRIBUTING.md#_snippet_1 + +LANGUAGE: markdown +CODE: +``` +[Development Guide](https://github.com/giampaolo/psutil/blob/master/docs/DEVGUIDE.rst) +``` + +---------------------------------------- + +TITLE: Windows Service Iteration and Retrieval +DESCRIPTION: Provides examples for iterating through all installed Windows services and retrieving specific services by name using psutil. Demonstrates accessing various attributes of a WindowsService object. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_80 + +LANGUAGE: python +CODE: +``` +import psutil + +# Iterate through all Windows services +print("Listing services:") +for service in psutil.win_service_iter(): + print(f"- {service.name()} ({service.display_name()})") + +# Get a specific Windows service +service_name = 'alg' +try: + s = psutil.win_service_get(service_name) + print(f"\nDetails for service '{service_name}':") + print(s.as_dict()) +except psutil.NoSuchProcess: + print(f"Service '{service_name}' not found.") +``` + +---------------------------------------- + +TITLE: Listing Windows Services +DESCRIPTION: Provides an example of how to list all available Windows services on the system. This is specific to Windows environments and requires administrative privileges. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_38 + +LANGUAGE: python +CODE: +``` +list(psutil.win_service_iter()) +``` + +---------------------------------------- + +TITLE: Installing psutil for Python 2.7 +DESCRIPTION: Instructions for installing the latest psutil version that supports Python 2.7. It specifies using pip with a version constraint to ensure compatibility. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_105 + +LANGUAGE: bash +CODE: +``` +$ python2 -m pip install psutil==6.1.* +``` + +---------------------------------------- + +TITLE: psutil.Process.memory_info() Example +DESCRIPTION: Demonstrates how to retrieve memory information for a process using psutil. Shows the output format and the types of metrics returned. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_69 + +LANGUAGE: python +CODE: +``` +import psutil + +p = psutil.Process() +mem_info = p.memory_info() +print(mem_info) +# Example Output: +pmem(rss=15491072, vms=84025344, shared=5206016, text=2555904, lib=0, data=9891840, dirty=0) +``` + +---------------------------------------- + +TITLE: Install Test Dependencies and Run Tests (Source Code) +DESCRIPTION: Installs pytest dependencies and runs all tests using the make command. This method is for users with the psutil source code. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/psutil/tests/README.rst#_snippet_0 + +LANGUAGE: bash +CODE: +``` +make install-pydeps-test +make test +``` + +---------------------------------------- + +TITLE: psutil Code Organization Structure +DESCRIPTION: Illustrates the directory and file structure of the psutil library, highlighting the placement of main namespace, platform-specific wrappers, C extensions, and test suites. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/DEVGUIDE.rst#_snippet_1 + +LANGUAGE: bash +CODE: +``` +psutil/__init__.py # main psutil namespace ("import psutil") +psutil/_ps{platform}.py # platform-specific python wrapper +psutil/_psutil_{platform}.c # platform-specific C extension +psutil/tests/test_process|system.py # main test suite +psutil/tests/test_{platform}.py # platform-specific test suite +``` + +---------------------------------------- + +TITLE: psutil API Documentation +DESCRIPTION: Documentation for key psutil functions and classes, including parameters, return values, and usage examples. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_365 + +LANGUAGE: APIDOC +CODE: +``` +psutil Module Documentation: + +High-level cross-platform library to retrieve information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python. + +Key Functions: + +- **cpu_times_percent(interval=None, percpu=False)** + - Returns system-wide CPU times percentages. + - Parameters: + - interval (float): If specified, block for 'interval' seconds and return the CPU times percentages. + - percpu (bool): If True, return a list of percentages for each CPU core. If False, return a single list with system-wide percentages. + - Returns: A float representing system-wide CPU usage percentage, or a list of floats if percpu is True. + - Example: + ```python + import psutil + print(psutil.cpu_times_percent(interval=1)) + print(psutil.cpu_times_percent(interval=1, percpu=True)) + ``` + +- **net_if_addrs()** + - Returns a dictionary mapping network interface names to a list of addresses associated with that interface. + - Returns: + - dict: A dictionary where keys are interface names (str) and values are lists of named tuples representing addresses. + - Each address tuple contains: `family` (e.g., AF_INET, AF_PACKET), `address`, `netmask`, `broadcast`, `ptp`. + - Example: + ```python + import psutil + print(psutil.net_if_addrs()) + ``` + +- **net_if_stats()** + - Returns network interface statistics. + - Returns: + - dict: A dictionary where keys are interface names (str) and values are named tuples with stats like `isup`, `duplex`, `speed`, `mtu`. + - Example: + ```python + import psutil + print(psutil.net_if_stats()) + ``` + +- **Process(pid)** + - Represents a running process. + - Parameters: + - pid (int): The process ID. + - Methods: + - **send_signal(signalnum)**: Sends a signal to the process. + - Parameters: + - signalnum (int): The signal number (e.g., signal.SIGTERM). + - Raises: + - AccessDenied: If the user lacks permissions. + - NoSuchProcess: If the process does not exist. + - **cpu_affinity(cores=None)**: Gets or sets the CPU affinity of the process. + - Parameters: + - cores (iterable): An iterable of integers representing CPU cores to which the process can be assigned. + - Returns: + - list: A list of integers representing the cores the process is currently assigned to. + - Raises: + - AccessDenied, NoSuchProcess, ValueError. + - **name()**: Returns the process name. + - Returns: + - str: The name of the process. + - Raises: + - AccessDenied, NoSuchProcess. + - **ionice(ioclass=None, value=None)**: Gets or sets the I/O scheduling class and priority. + - Parameters: + - ioclass (int): The I/O class (e.g., psutil.IOPRIO_CLASS_BE). + - value (int): The I/O priority value. + - Returns: + - namedtuple: With fields `ioclass` and `value`. + - Raises: + - AccessDenied, NoSuchProcess, NotImplementedError, ValueError. + - **nice(n=None)**: Gets or sets the scheduling priority of the process. + - Parameters: + - n (int): The priority value. + - Returns: + - int: The priority value. + - Raises: + - AccessDenied, NoSuchProcess, NotImplementedError. + - **open_files()**: Returns a list of files opened by the process. + - Returns: + - list: A list of named tuples, each representing an open file with fields `path`, `fd`. + - Raises: + - AccessDenied, NoSuchProcess. + +- **users()** + - Returns a list of logged-in users. + - Returns: + - list: A list of named tuples, each representing a logged-in user with fields `name`, `terminal`, `host`, `started`, `pid`. + - Example: + ```python + import psutil + print(psutil.users()) + ``` + +Exceptions: + +- **ZombieProcess**: Raised when interacting with a zombie process. +- **AccessDenied**: Raised when access to process information is denied. +- **NoSuchProcess**: Raised when a process with the specified PID does not exist. +- **TimeoutExpired**: Raised when an operation times out. +- **Error**: Base class for psutil exceptions. +``` + +---------------------------------------- + +TITLE: Windows 64-bit Installer +DESCRIPTION: Provides an installer for 64-bit Windows systems, specifically for Python 3.X. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_412 + +LANGUAGE: python +CODE: +``` +# Enhancement: installer for Python 3.X 64 bit on Windows. +# Implemented in psutil version 2.0.0 +``` + +---------------------------------------- + +TITLE: Setup.py Dependency Compatibility +DESCRIPTION: Resolves an issue with setup.py where the 'extra_require' parameter required the latest setuptools version, which caused installation problems. This ensures broader compatibility with different setuptools versions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_209 + +LANGUAGE: python +CODE: +``` +# setup.py's "extra_require" parameter requires latest setuptools version, breaking quite a lot of installations. +``` + +---------------------------------------- + +TITLE: psutil Pull Request Workflow +DESCRIPTION: Steps for contributing code to psutil, including forking the repository, cloning, creating a branch, committing changes, pushing, and creating a pull request on GitHub. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/DEVGUIDE.rst#_snippet_2 + +LANGUAGE: bash +CODE: +``` +git clone git@github.com:YOUR-USERNAME/psutil.git +git checkout -b new-feature +git commit -am 'add some feature' +git push origin new-feature +``` + +---------------------------------------- + +TITLE: Easy Install Warnings Fix +DESCRIPTION: Fixes warnings that occurred when installing psutil with easy_install. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_526 + +LANGUAGE: python +CODE: +``` +# Installation with easy_install is now warning-free. +``` + +---------------------------------------- + +TITLE: Get Boot Time +DESCRIPTION: Returns the system boot time as a Unix timestamp. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_22 + +LANGUAGE: python +CODE: +``` +psutil.boot_time() +# Output: 1365519115.0 +``` + +---------------------------------------- + +TITLE: psutil API Documentation +DESCRIPTION: This section provides documentation for key psutil functions and methods, including their parameters, return values, and usage examples. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_41 + +LANGUAGE: APIDOC +CODE: +``` +psutil.disk_partitions(all=True) + - Returns a list of namedtuples representing disk partitions. + - Parameters: + - all (bool): If True, include all partitions (including CD-ROM, RAM disk, etc.). Defaults to True. + - Returns: + - list: A list of namedtuples, where each namedtuple contains: + - device (str): Partition device name. + - mountpoint (str): Mount point. + - fstype (str): Filesystem type. + - opts (str): Mount options. + - maxfile (int): Maximum length of a filename (removed in 6.0.0). + - maxpath (int): Maximum length of a path (removed in 6.0.0). + - Note: 'maxfile' and 'maxpath' fields were removed in psutil 6.0.0 due to potential performance issues on network filesystems. + +psutil.process_iter(attrs=None, reverse=False) + - Returns an iterator yielding Process instances for all running processes. + - Parameters: + - attrs (list, optional): A list of attributes to prefetch for each process. Prefetching can speed up subsequent attribute access. + - reverse (bool): If True, iterate processes in reverse order (from highest PID to lowest). + - Returns: + - iterator: An iterator yielding psutil.Process objects. + - Note: As of 6.0.0, PID reuse is no longer pre-emptively checked. Use Process.is_running() to check if a PID has been reused. + +psutil.process_iter.cache_clear() + - Clears the internal cache used by psutil.process_iter(). + +Process.num_fds() + - Returns the number of file descriptors opened by this process. + - Returns: + - int: The number of file descriptors. + - Raises: + - psutil.NoSuchProcess: If the process has ended. + - psutil.AccessDenied: If run as a non-root user on some platforms. + +Process.open_files() + - Returns a list of namedtuples representing the files opened by this process. + - Returns: + - list: A list of namedtuples, each containing: + - path (str): Path to the file. + - fd (int): File descriptor number. + - Raises: + - psutil.NoSuchProcess: If the process has ended. + - psutil.AccessDenied: If run as a non-root user on some platforms. + +Process.net_connections(kind='inet') + - Returns a list of network connections opened by this process. + - Parameters: + - kind (str): Type of connections to return ('inet', 'tcp', 'udp', 'unix'). Defaults to 'inet' (TCP and UDP). + - Returns: + - list: A list of namedtuples, each representing a connection with details like laddr, raddr, status, type, etc. + - Raises: + - psutil.NoSuchProcess: If the process has ended. + - psutil.AccessDenied: If run as a non-root user on some platforms. + - Note: This method was previously named Process.connections(). + +Process.cpu_freq(percpu=False) + - Returns CPU frequency information. + - Parameters: + - percpu (bool): If True, return a list of frequencies for each CPU core. Defaults to False. + - Returns: + - float or list: Current CPU frequency in MHz, or a list of frequencies if percpu is True. + - Raises: + - NotImplementedError: If CPU frequency information is not available on the system. + - psutil.NoSuchProcess: If the process has ended. + - psutil.AccessDenied: If run as a non-root user on some platforms. + +Process.cwd() + - Returns the current working directory of this process. + - Returns: + - str: The path of the current working directory. + - Raises: + - psutil.NoSuchProcess: If the process has ended. + - psutil.AccessDenied: If run as a non-root user on some platforms. + - Note: On NetBSD, if the process has terminated, this method returns an empty string. + +Process.ppid() + - Returns the PID of the parent process. + - Returns: + - int: The PID of the parent process. + - Raises: + - psutil.NoSuchProcess: If the process has ended. + - psutil.AccessDenied: If run as a non-root user on some platforms. + +Process.parents() + - Returns a list of parent Process objects, starting from the immediate parent up to PID 1. + - Returns: + - list: A list of psutil.Process objects representing the parent processes. + - Raises: + - psutil.NoSuchProcess: If the process has ended. + - psutil.AccessDenied: If run as a non-root user on some platforms. + +psutil.cpu_percent(interval=None, percpu=False) + - Returns the system-wide CPU utilization as a percentage. + - Parameters: + - interval (float, optional): Sampling interval in seconds. If None, return instantly. + - percpu (bool): If True, return a list of percentages for each CPU core. Defaults to False. + - Returns: + - float or list: System-wide CPU utilization percentage, or a list if percpu is True. + - Note: This function is thread-safe as of psutil 5.9.6. + +psutil.cpu_times_percent(interval=None, percpu=False) + - Returns system-wide CPU times spent in various modes (user, system, idle, etc.) as percentages. + - Parameters: + - interval (float, optional): Sampling interval in seconds. If None, return instantly. + - percpu (bool): If True, return percentages for each CPU core. Defaults to False. + - Returns: + - float or list: A namedtuple or list of namedtuples containing CPU time percentages. + - Note: This function is thread-safe as of psutil 5.9.6. + +psutil.pid_exists(pid) + - Returns True if a process with the given PID exists, False otherwise. + - Parameters: + - pid (int): The process ID to check. + - Returns: + - bool: True if the process exists, False otherwise. + - Note: On Windows, this function may disagree with Process() on whether a PID exists when ERROR_ACCESS_DENIED is encountered. + - Note: On OpenBSD, this function may erroneously return True if the argument is a thread ID (TID) instead of a PID. + +psutil.Process(pid) + - Returns a Process object representing the process with the given PID. + - Parameters: + - pid (int): The process ID. + - Returns: + - psutil.Process: A Process object. + - Raises: + - psutil.NoSuchProcess: If the process with the given PID does not exist. + - psutil.AccessDenied: If the current user does not have permission to access the process information. + - OverflowError: If the PID is too large (handled as NoSuchProcess in 5.9.6+). + +``` + +---------------------------------------- + +TITLE: List Logged-in Users +DESCRIPTION: Returns a list of tuples, each representing a logged-in user with their name, terminal, host, start time, and PID. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_21 + +LANGUAGE: python +CODE: +``` +psutil.users() +# Output: [suser(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0, pid=1352), suser(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0, pid=1788)] +``` + +---------------------------------------- + +TITLE: Process Iteration Example +DESCRIPTION: Demonstrates how to iterate through processes, retrieve their names and CPU times, and sort them by CPU usage. It uses a list comprehension to extract relevant information and then sorts the processes to find the top 3 CPU consumers. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_100 + +LANGUAGE: python +CODE: +``` +import psutil + +# Get the top 3 processes by CPU time +# pp([(p.pid, p.info['name'], sum(p.info['cpu_times'])) for p in sorted(psutil.process_iter(['name', 'cpu_times']), key=lambda p: sum(p.info['cpu_times'][:2]))][-3:]) +``` + +---------------------------------------- + +TITLE: Install System Dependencies +DESCRIPTION: Enhancement for psutil version 6.1.0: Added 'make install-sysdeps' target to install necessary system dependencies (python-dev, gcc, etc.) on supported UNIX flavors. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_27 + +LANGUAGE: bash +CODE: +``` +make install-sysdeps +``` + +---------------------------------------- + +TITLE: Install Development and Test Dependencies +DESCRIPTION: Enhancement for psutil version 6.1.0: Added 'make install-pydeps-test' and 'make install-pydeps-dev' targets for installing development and testing dependencies. Can also be installed via pip. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_28 + +LANGUAGE: bash +CODE: +``` +make install-pydeps-test +make install-pydeps-dev +``` + +LANGUAGE: bash +CODE: +``` +pip install .[test] +pip install .[dev] +``` + +---------------------------------------- + +TITLE: make install with Virtualenv +DESCRIPTION: Ensures that 'make install' works correctly even when psutil is installed within a Python virtual environment. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_305 + +LANGUAGE: bash +CODE: +``` +# Ensure you are in a virtual environment: +# source /path/to/venv/bin/activate +# Then run the installation: +# pip install . +# Or if building from source: +# python setup.py install +``` + +---------------------------------------- + +TITLE: psutil Test Function +DESCRIPTION: Executes a test function within psutil that displays a table of running processes, similar to the 'top' command, showing PID, CPU usage, memory usage, TTY, start time, and command. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_34 + +LANGUAGE: python +CODE: +``` +psutil.test() +# Expected output: +# USER PID %CPU %MEM VSZ RSS TTY START TIME COMMAND +# root 1 0.0 0.0 24584 2240 Jun17 00:00 init +# root 2 0.0 0.0 0 0 Jun17 00:00 kthreadd +# ... +# giampaolo 31475 0.0 0.0 20760 3024 /dev/pts/0 Jun19 00:00 python2.4 +# giampaolo 31721 0.0 2.2 773060 181896 00:04 10:30 chrome +# root 31763 0.0 0.0 0 0 00:05 00:00 kworker/0:1 +# ... +``` + +---------------------------------------- + +TITLE: Process Environment Variables +DESCRIPTION: Gets the environment variables of the process as a dictionary. Note that this might not reflect changes made after the process started. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_40 + +LANGUAGE: APIDOC +CODE: +``` +environ() + Returns the environment variables of the process as a dict. + Note: this might not reflect changes made after the process started. + Example: + >>> import psutil + >>> psutil.Process().environ() + Returns: A dictionary of environment variables. +``` + +---------------------------------------- + +TITLE: psutil Process Class Methods +DESCRIPTION: Documentation for psutil's Process class methods, detailing their functionality, parameters, return values, and usage examples. Includes version information for added features and changes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_43 + +LANGUAGE: APIDOC +CODE: +``` +.. method:: create_time() + + The process creation time as a floating point number expressed in seconds + since the epoch (seconds since January 1, 1970, at midnight UTC). The + return value, which is cached after first call, is based on the system + clock, which means it may be affected by changes such as manual adjustments + or time synchronization (e.g. NTP). + + >>> import psutil, datetime + >>> p = psutil.Process() + >>> p.create_time() + 1307289803.47 + >>> datetime.datetime.fromtimestamp(p.create_time()).strftime("%Y-%m-%d %H:%M:%S") + '2011-03-05 18:03:52' + +.. versionadded:: 4.0.0 +.. versionchanged:: 5.3.0 added SunOS support +.. versionchanged:: 5.6.3 added AIX support +.. versionchanged:: 5.7.3 added BSD support + +.. method:: as_dict(attrs=None, ad_value=None) + + Utility method retrieving multiple process information as a dictionary. + If *attrs* is specified it must be a list of strings reflecting available + :class:`Process` class's attribute names. Here's a list of possible string + values: + ``'cmdline'``, ``'net_connections'``, ``'cpu_affinity'``, ``'cpu_num'``, ``'cpu_percent'``, ``'cpu_times'``, ``'create_time'``, ``'cwd'``, ``'environ'``, ``'exe'``, ``'gids'``, ``'io_counters'``, ``'ionice'``, ``'memory_full_info'``, ``'memory_info'``, ``'memory_maps'``, ``'memory_percent'``, ``'name'``, ``'nice'``, ``'num_ctx_switches'``, ``'num_fds'``, ``'num_handles'``, ``'num_threads'``, ``'open_files'``, ``'pid'``, ``'ppid'``, ``'status'``, ``'terminal'``, ``'threads'``, ``'uids'``, ``'username'```. + If *attrs* argument is not passed all public read only attributes are + assumed. + *ad_value* is the value which gets assigned to a dict key in case + an exception occurs during attribute retrieval. +``` + +---------------------------------------- + +TITLE: Installation with PYTHONOPTIMIZE=2 Fix +DESCRIPTION: Resolves an issue preventing psutil installation when the PYTHONOPTIMIZE=2 environment variable is set. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_258 + +LANGUAGE: python +CODE: +``` +# Bug fix: cannot install psutil with PYTHONOPTIMIZE=2. +# This ensures psutil can be installed in optimized Python builds. +``` + +---------------------------------------- + +TITLE: Windows make.bat Enhancement +DESCRIPTION: The make.bat script on Windows is now smarter in finding alternative Visual Studio installation locations, improving the build process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_352 + +LANGUAGE: batch +CODE: +``` +make.bat +``` + +---------------------------------------- + +TITLE: Process Priority Constants (Windows) +DESCRIPTION: Constants representing process priority classes on Windows. These can be used with psutil.Process.nice() to get or set process priority. Examples include REALTIME_PRIORITY_CLASS, HIGH_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, etc. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_86 + +LANGUAGE: python +CODE: +``` +import psutil + +process = psutil.Process(pid) +# Example: Set process priority to High +# process.nice(psutil.HIGH_PRIORITY_CLASS) +# Example: Get process priority +# priority = process.nice() + +``` + +---------------------------------------- + +TITLE: Process Niceness (Priority) Management +DESCRIPTION: Allows getting or setting the process niceness (priority). On UNIX, it's a value typically from -20 to 20, where higher values mean lower priority. On Windows, it uses priority classes like `HIGH_PRIORITY_CLASS`. Examples demonstrate setting and getting niceness. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_50 + +LANGUAGE: APIDOC +CODE: +``` +.. method:: nice(value=None) + + Get or set process niceness (priority). + On UNIX this is a number which usually goes from ``-20`` to ``20``. + The higher the nice value, the lower the priority of the process. + + >>> import psutil + >>> p = psutil.Process() + >>> p.nice(10) # set + >>> p.nice() # get + 10 + >>> + + Starting from Python 3.3 this functionality is also available as + `os.getpriority`_ and `os.setpriority`_ (see `BPO-10784`_). + On Windows this is implemented via `GetPriorityClass`_ and + `SetPriorityClass`_ Windows APIs and *value* is one of the + :data:`psutil.*_PRIORITY_CLASS ` + constants reflecting the MSDN documentation. + Example which increases process priority on Windows: + + >>> p.nice(psutil.HIGH_PRIORITY_CLASS) +``` + +---------------------------------------- + +TITLE: Process I/O Niceness (Priority) Management +DESCRIPTION: Allows getting or setting the process I/O niceness (priority). On Linux, it supports classes like `IOPRIO_CLASS_RT`, `IOPRIO_CLASS_BE`, `IOPRIO_CLASS_IDLE`, with optional value levels. On Windows, it uses classes like `IOPRIO_HIGH` and `IOPRIO_NORMAL`. The method returns a tuple or integer depending on the platform and whether it's a get or set operation. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_51 + +LANGUAGE: APIDOC +CODE: +``` +.. method:: ionice(ioclass=None, value=None) + + Get or set process I/O niceness (priority). + If no argument is provided it acts as a get, returning a ``(ioclass, value)`` + tuple on Linux and a *ioclass* integer on Windows. + If *ioclass* is provided it acts as a set. In this case an additional + *value* can be specified on Linux only in order to increase or decrease the + I/O priority even further. + Here's the possible platform-dependent *ioclass* values. + + Linux (see `ioprio_get`_ manual): + + * ``IOPRIO_CLASS_RT``: (high) the process gets first access to the disk + every time. Use it with care as it can starve the entire + system. Additional priority *level* can be specified and ranges from + ``0`` (highest) to ``7`` (lowest). + * ``IOPRIO_CLASS_BE``: (normal) the default for any process that hasn't set + a specific I/O priority. Additional priority *level* ranges from + ``0`` (highest) to ``7`` (lowest). + * ``IOPRIO_CLASS_IDLE``: (low) get I/O time when no-one else needs the disk. + No additional *value* is accepted. + * ``IOPRIO_CLASS_NONE``: returned when no priority was previously set. + + Windows: + + * ``IOPRIO_HIGH``: highest priority. + * ``IOPRIO_NORMAL``: default priority. +``` + +---------------------------------------- + +TITLE: psutil Process API +DESCRIPTION: Documentation for psutil Process methods. + +- **cpu_times()**: Returns process CPU times (user, system, children_user, children_system, iowait). +- **cpu_percent(interval=None)**: Returns process CPU utilization percentage. Blocking with interval > 0, non-blocking otherwise. First call returns 0.0. +- **cpu_affinity(cpus=None)**: Gets or sets CPU affinity. Accepts a list of CPU IDs. An empty list resets affinity. +- **cpu_num()**: Returns the CPU the process is running on. +- **memory_info()**: Returns memory information (rss, vms, etc.). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_67 + +LANGUAGE: APIDOC +CODE: +``` +Process: + cpu_times() -> pcputimes + Returns a tuple of floating point numbers representing the seconds the process spent in user and system mode, plus system and user mode for children processes and optionally iowait time. + Fields: user, system, children_user, children_system, iowait + + cpu_percent(interval: Optional[float] = None) -> float + Return a float representing the process CPU utilization as a percentage. + Can be > 100.0 for multi-threaded processes. + If interval is > 0.0, it blocks for that interval and compares process times. + If interval is 0.0 or None, it compares process times since last call (non-blocking). + The first call with interval=None or 0.0 returns 0.0. + + cpu_affinity(cpus: Optional[List[int]] = None) -> List[int] + Get or set process CPU affinity. + If no argument is passed, returns the current CPU affinity as a list of integers. + If passed, it must be a list of integers specifying the new CPUs affinity. + An empty list resets affinity to all eligible CPUs. + Availability: Linux, Windows, FreeBSD + + cpu_num() -> int + Return what CPU this process is currently running on. + Availability: Linux, FreeBSD, SunOS + + memory_info() -> pmmap_grouped + Return a named tuple with memory information about the process. + Portable fields: rss, vms +``` + +---------------------------------------- + +TITLE: CPU Frequency +DESCRIPTION: Gets the current, minimum, and maximum CPU frequency. Dependencies: None. Returns a named tuple. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_7 + +LANGUAGE: python +CODE: +``` +>>> psutil.cpu_freq() +scpufreq(current=931.42925, min=800.0, max=3500.0) +``` + +---------------------------------------- + +TITLE: Process Nice Value and I/O Priority +DESCRIPTION: Allows getting and setting the 'nice' value (scheduling priority) of a process. Also retrieves and sets the I/O priority on supported systems (Linux and Windows). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_31 + +LANGUAGE: python +CODE: +``` +p.nice() +# Expected output: 0 + +p.nice(10) # set + +p.ionice(psutil.IOPRIO_CLASS_IDLE) # IO priority (Win and Linux only) + +p.ionice() +# Expected output: pionice(ioclass=, value=0) +``` + +---------------------------------------- + +TITLE: Process Set Methods Renamed +DESCRIPTION: This section details the renaming of `Process` class methods that previously started with `set_`. These methods are now direct methods without the `set_` prefix. For example, `p.set_nice()` is now `p.nice(value)`. This change aims for a more consistent and Pythonic API. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_436 + +LANGUAGE: python +CODE: +``` +Assuming p = psutil.Process(): + +p.nice(value) # Formerly p.set_nice() +p.ionice(ioclass, value=None) # Formerly p.set_ionice() +p.cpu_affinity(cpus) # Formerly p.set_cpu_affinity() +p.rlimit(resource, limits=None) # Formerly p.set_rlimit() +``` + +---------------------------------------- + +TITLE: Get System Load Average +DESCRIPTION: Retrieves the system load average for the last 1, 5, and 15 minutes. This function is available on Windows through emulation. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_8 + +LANGUAGE: python +CODE: +``` +psutil.getloadavg() +# Output: (3.14, 3.89, 4.67) +``` + +---------------------------------------- + +TITLE: Process CPU Usage and Affinity +DESCRIPTION: Calculates the CPU utilization percentage of the process over a specified interval. Also allows getting and setting the CPU affinity of the process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_27 + +LANGUAGE: python +CODE: +``` +p.cpu_percent(interval=1.0) +# Expected output: 12.1 + +p.cpu_affinity() +# Expected output: [0, 1, 2, 3] + +p.cpu_affinity([0, 1]) # set + +p.cpu_num() +# Expected output: 1 +``` + +---------------------------------------- + +TITLE: System Uptime and Memory Information +DESCRIPTION: Provides functions for retrieving system-wide information, including `boot_time()` for system uptime, and functions to get total physical and virtual memory, as well as used and free memory statistics. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_548 + +LANGUAGE: python +CODE: +``` +boot_time() +# Total system memory functions +# Used/free memory functions +``` + +---------------------------------------- + +TITLE: Wheel Package Distribution on Windows +DESCRIPTION: Enables distribution of psutil as wheel packages for easier installation on Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_411 + +LANGUAGE: python +CODE: +``` +# Enhancement: distribution as wheel packages on Windows. +# Implemented in psutil version 2.1.2 +``` + +---------------------------------------- + +TITLE: Process Niceness (Priority) +DESCRIPTION: Allows getting and setting the niceness (priority) of a process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_498 + +LANGUAGE: python +CODE: +``` +p.nice() +``` + +---------------------------------------- + +TITLE: Filter Processes by Username +DESCRIPTION: This example demonstrates how to filter processes to find those owned by the current user. It retrieves the username for each process and compares it with the system's current user. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_96 + +LANGUAGE: python +CODE: +``` +import psutil +import getpass +from pprint import pprint as pp + +pp([(p.pid, p.info['name']) for p in psutil.process_iter(['name', 'username']) if p.info['username'] == getpass.getuser()]) +``` + +---------------------------------------- + +TITLE: Find Processes Using Log Files +DESCRIPTION: This example iterates through processes and checks their open files to identify those that have files ending with '.log'. It prints the process ID, name, and the path to the log file. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_98 + +LANGUAGE: python +CODE: +``` +import psutil + +for p in psutil.process_iter(['name', 'open_files']): + for file in p.info['open_files'] or []: + if file.path.endswith('.log'): + print("%-5s %-10s %s" % (p.pid, p.info['name'][:10], file.path)) +``` + +---------------------------------------- + +TITLE: Currently Connected Users +DESCRIPTION: Returns a list of users currently connected to the system. Each entry includes username, terminal, host, start time, and login process PID (where available). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_25 + +LANGUAGE: python +CODE: +``` +import psutil + +users = psutil.users() +for user in users: + print(f"User: {user.name}, Terminal: {user.terminal}, Host: {user.host}, Started: {user.started}, PID: {user.pid}") +``` + +---------------------------------------- + +TITLE: pyproject.toml removal +DESCRIPTION: Removes the pyproject.toml file, which was causing installation issues. This simplifies the build process and improves compatibility with various installation tools. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_123 + +LANGUAGE: python +CODE: +``` +# Build system configuration adjustment. +``` + +---------------------------------------- + +TITLE: C Extension Version Mismatch Detection +DESCRIPTION: Implements detection of C extension version mismatches at import time to help users with installation issues. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_398 + +LANGUAGE: python +CODE: +``` +# Enhancement: C extension version mismatch in case the user messed up with psutil installation or with sys.path is now detected at import time. +# Implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: pyproject.toml removal +DESCRIPTION: Removes the pyproject.toml file, which was causing installation issues. This simplifies the build process and improves compatibility with various installation tools. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_152 + +LANGUAGE: python +CODE: +``` +# Build system configuration adjustment. +``` + +---------------------------------------- + +TITLE: Process Resource Limit Constants +DESCRIPTION: Constants used with psutil.Process.rlimit() to get or set process resource limits. These include general limits like RLIMIT_NOFILE, RLIMIT_NPROC, and platform-specific limits for Linux and FreeBSD. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_89 + +LANGUAGE: python +CODE: +``` +import psutil + +process = psutil.Process(pid) +# Example: Get the maximum number of open files +# soft_limit, hard_limit = process.rlimit(psutil.RLIMIT_NOFILE) +# print(f"Soft limit: {soft_limit}, Hard limit: {hard_limit}") + +``` + +---------------------------------------- + +TITLE: Disk Usage Statistics (disk_usage()) +DESCRIPTION: Introduces disk_usage() to get disk usage statistics for a given path. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_488 + +LANGUAGE: python +CODE: +``` +import psutil + +usage = psutil.disk_usage('/') +print(f'Total: {usage.total}, Used: {usage.used}, Free: {usage.free}') +``` + +---------------------------------------- + +TITLE: Windows Service Iteration and Get +DESCRIPTION: Introduces new APIs, win_service_iter() and win_service_get(), for managing Windows services. These allow iteration over services and retrieval of specific service information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_286 + +LANGUAGE: python +CODE: +``` +from psutil import win_service_iter, win_service_get + +# Iterate over all services +for svc in win_service_iter(): + print(f"Service: {svc.name}") + +# Get a specific service by name (replace 'YourServiceName') +try: + specific_svc = win_service_get('YourServiceName') + print(f"Details for YourServiceName: {specific_svc}") +except Exception as e: + print(f"Could not get service: {e}") +``` + +---------------------------------------- + +TITLE: Disk Partitions +DESCRIPTION: Returns a list of tuples, each representing a disk partition with device, mountpoint, filesystem type, and options. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_11 + +LANGUAGE: python +CODE: +``` +psutil.disk_partitions() +# Output: [sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid'), sdiskpart(device='/dev/sda2', mountpoint='/home', fstype='ext', opts='rw')] +``` + +---------------------------------------- + +TITLE: Process.rlimit() Enhancement +DESCRIPTION: Added support for getting and setting process resource limits using the `Process.rlimit()` method, particularly for Linux systems. This allows finer control over system resource usage for individual processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_441 + +LANGUAGE: python +CODE: +``` +import psutil +import resource + +p = psutil.Process() + +# Get current limits for a resource +soft_limit, hard_limit = p.rlimit(resource.RLIMIT_NOFILE) +print(f"Soft limit: {soft_limit}, Hard limit: {hard_limit}") + +# Set new limits (example: increase open file limit) +# p.rlimit(resource.RLIMIT_NOFILE, (1024, 4096)) +``` + +---------------------------------------- + +TITLE: psutil API Renames - Process Methods +DESCRIPTION: All 'get_*' methods on the Process class have been renamed by removing the 'get_' prefix for improved consistency. For example, 'get_ext_memory_info()' is now 'memory_info_ex()'. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_421 + +LANGUAGE: APIDOC +CODE: +``` +All Process.* "get_*" methods lost the "get_" prefix. +Example: Assuming p = psutil.Process() + +Old name: p.get_children() +Replacement: p.children() + +Old name: p.get_connections() +Replacement: p.connections() + +Old name: p.get_cpu_affinity() +Replacement: p.cpu_affinity() + +Old name: p.get_cpu_percent() +Replacement: p.cpu_percent() + +Old name: p.get_cpu_times() +Replacement: p.cpu_times() + +Old name: p.get_ext_memory_info() +Replacement: p.memory_info_ex() + +Old name: p.get_io_counters() +Replacement: p.io_counters() + +Old name: p.get_ionice() +Replacement: p.ionice() + +Old name: p.get_memory_info() +Replacement: p.memory_info() + +Old name: p.get_memory_maps() +Replacement: p.memory_maps() + +Old name: p.get_memory_percent() +Replacement: p.memory_percent() + +Old name: p.get_nice() +Replacement: p.nice() + +Old name: p.get_num_ctx_switches() +Replacement: p.num_ctx_switches() + +Old name: p.get_num_fds() +Replacement: p.num_fds() + +Old name: p.get_num_threads() +Replacement: p.num_threads() + +Old name: p.get_open_files() +Replacement: p.open_files() + +Old name: p.get_rlimit() +Replacement: p.rlimit() + +Old name: p.get_threads() +Replacement: p.threads() + +Old name: p.getcwd() +Replacement: p.cwd() +``` + +---------------------------------------- + +TITLE: Process Resource Limits (rlimit) +DESCRIPTION: Enables getting or setting process resource limits, such as the maximum number of open file descriptors or the maximum file size. It accepts resource constants and a tuple of (soft, hard) limits. Values can be integers or psutil.RLIM_INFINITY. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_53 + +LANGUAGE: python +CODE: +``` +import psutil + +p = psutil.Process() + +# Set limits for file descriptors and file size +p.rlimit(psutil.RLIMIT_NOFILE, (128, 128)) +p.rlimit(psutil.RLIMIT_FSIZE, (1024, 1024)) + +# Get current limits for file size +print(p.rlimit(psutil.RLIMIT_FSIZE)) +``` + +---------------------------------------- + +TITLE: Process Working Directory +DESCRIPTION: Gets the current working directory of the process. Returns an absolute path. If the directory cannot be determined (e.g., system process, non-existent directory), it may return an empty string. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_47 + +LANGUAGE: APIDOC +CODE: +``` +.. method:: cwd() + + The process current working directory as an absolute path. If cwd cannot be + determined for some internal reason (e.g. system process or directory no + longer exists) it may return an empty string. + + .. versionchanged:: 5.6.4 added support for NetBSD +``` + +---------------------------------------- + +TITLE: Get System Load Average +DESCRIPTION: Returns the system load average over the last 1, 5, and 15 minutes. Load represents runnable processes (CPU or I/O bound). On Windows, it's emulated and initially returns (0.0, 0.0, 0.0) for 5 seconds. Values should be compared to the number of CPU cores. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_8 + +LANGUAGE: python +CODE: +``` +>>> import psutil +>>> psutil.getloadavg() +(3.14, 3.89, 4.67) +>>> psutil.cpu_count() +10 +>>> # percentage representation +>>> [x / psutil.cpu_count() * 100 for x in psutil.getloadavg()] +[31.4, 38.9, 46.7] +``` + +---------------------------------------- + +TITLE: Process Object and Attributes +DESCRIPTION: Demonstrates creating a Process object and accessing its attributes like PID, name, executable path, current working directory, and command line. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_24 + +LANGUAGE: python +CODE: +``` +p = psutil.Process(7055) +print(p) +print(p.pid) +print(p.name()) +print(p.exe()) +print(p.cwd()) +print(p.cmdline()) +# Output: +# psutil.Process(pid=7055, name='python3', status='running', started='09:04:44') +# 7055 +# python3 +# /usr/bin/python3 +# /home/giampaolo +# ['/usr/bin/python3'] +``` + +---------------------------------------- + +TITLE: Setuptools Integration +DESCRIPTION: Integrates setuptools into the setup.py script for improved package management. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_490 + +LANGUAGE: python +CODE: +``` +# setup.py now uses setuptools for installation. +``` + +---------------------------------------- + +TITLE: Per-Process Associated Terminal (Process.terminal()) +DESCRIPTION: Introduces Process.terminal() to get the associated terminal (TTY) for a process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_486 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +p = Process() +terminal = p.terminal() +``` + +---------------------------------------- + +TITLE: Process I/O Priority Management +DESCRIPTION: Allows setting and getting the I/O priority of a process. The available constants and behavior may vary by operating system. On Linux, it accepts a class and a value, while on Windows, it accepts predefined constants like IOPRIO_HIGH. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_52 + +LANGUAGE: python +CODE: +``` +import psutil + +p = psutil.Process() + +# Set highest I/O priority +if psutil.LINUX: + p.ionice(psutil.IOPRIO_CLASS_RT, value=7) +else: + p.ionice(psutil.IOPRIO_HIGH) + +# Get current I/O priority +print(p.ionice()) +``` + +---------------------------------------- + +TITLE: Process Status +DESCRIPTION: Provides a method to get the status of a process. Fixes an issue where it could raise unhandled exceptions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_499 + +LANGUAGE: python +CODE: +``` +p.status() +``` + +---------------------------------------- + +TITLE: Get All Running PIDs +DESCRIPTION: Returns a sorted list of all currently running process IDs (PIDs). For iterating over processes safely, `process_iter()` is recommended. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_26 + +LANGUAGE: python +CODE: +``` +import psutil + +# Get a sorted list of all PIDs +pids = psutil.pids() +print(pids) +``` + +---------------------------------------- + +TITLE: Per-Process User and Group IDs +DESCRIPTION: Provides methods to get real, effective, and saved user and group IDs for a process. Deprecates uid/gid properties in favor of uids/gids. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_496 + +LANGUAGE: python +CODE: +``` +p.gids() +``` + +LANGUAGE: python +CODE: +``` +p.uids() +``` + +---------------------------------------- + +TITLE: Battery Status +DESCRIPTION: Retrieves battery status information including percentage, time left, and power plug status. Returns None if no battery is installed or metrics cannot be determined. Available on Linux, Windows, and FreeBSD. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_23 + +LANGUAGE: python +CODE: +``` +import psutil +import datetime + +def secs2hours(secs): + mm, ss = divmod(secs, 60) + hh, mm = divmod(mm, 60) + return "%d:%02d:%02d" % (hh, mm, ss) + +battery = psutil.sensors_battery() +if battery: + print(f"Battery Percent: {battery.percent}%") + print(f"Time Left: {secs2hours(battery.secsleft)}") + print(f"Power Plugged: {battery.power_plugged}") +else: + print("Battery information not available.") +``` + +---------------------------------------- + +TITLE: Threading +DESCRIPTION: This section covers basic threading functionalities in Python, including getting the current thread's identifier and creating new threads. It references the `threading` module. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_116 + +LANGUAGE: APIDOC +CODE: +``` +threading.get_ident() + - Return the 'thread identifier' of the current thread. + - Returns: An integer identifying the current thread. + +threading.Thread + - Represents a thread of execution. + - Usage: + thread = threading.Thread(target=my_function, args=(arg1, arg2)) + thread.start() + thread.join() + +``` + +LANGUAGE: python +CODE: +``` +import threading + +# Get the identifier of the current thread +thread_id = threading.get_ident() +print(f"Current thread ID: {thread_id}") + +# Example of creating and starting a thread +def worker_function(): + print(f"Worker thread started (ID: {threading.get_ident()})") + +worker_thread = threading.Thread(target=worker_function) +worker_thread.start() +worker_thread.join() # Wait for the worker thread to complete +print("Worker thread finished.") + +``` + +---------------------------------------- + +TITLE: psutil API Functions for Windows Services +DESCRIPTION: Details the psutil functions for interacting with Windows services: win_service_iter() to get an iterator for all services, and win_service_get(name) to retrieve a specific service by its name. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_83 + +LANGUAGE: APIDOC +CODE: +``` +win_service_iter(): + Returns an iterator yielding WindowsService instances for all installed services. + Availability: Windows + +win_service_get(name): + Retrieves a WindowsService instance by its name. + Raises psutil.NoSuchProcess if the service is not found. + Availability: Windows + + Example: + >>> services = list(psutil.win_service_iter()) + >>> print(f"Found {len(services)} services.") + >>> running_services = [s.name() for s in services if s.status() == 'running'] + >>> print(f"Running services: {running_services}") +``` + +---------------------------------------- + +TITLE: psutil Module Overview +DESCRIPTION: This section provides a general overview of the psutil module, its purpose, supported platforms, and Python versions. It highlights psutil's utility for system monitoring, profiling, and process management, drawing parallels to common UNIX command-line tools. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_0 + +LANGUAGE: python +CODE: +``` +.. module:: psutil + :synopsis: psutil module +.. moduleauthor:: Giampaolo Rodola' + +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 mainly for **system monitoring**, **profiling**, **limiting +process resources** and the **management of running processes**. +It implements many functionalities offered by UNIX command line tools +such as: *ps, top, lsof, netstat, ifconfig, who, df, kill, free, nice, +ionice, iostat, iotop, uptime, pidof, tty, taskset, pmap*. +psutil currently supports the following platforms: + +- **Linux** +- **Windows** +- **macOS** +- **FreeBSD, OpenBSD**, **NetBSD** +- **Sun Solaris** +- **AIX** + +Supported Python versions are **2.7** and **3.6+**. +`PyPy `__ is also known to work. +``` + +---------------------------------------- + +TITLE: Process Status and Timing +DESCRIPTION: Gets the current status of the process (e.g., 'running', 'sleeping') and its creation time. Also retrieves CPU time spent by the process in user and system mode, including time spent by children. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_26 + +LANGUAGE: python +CODE: +``` +p.status() +# Expected output: 'running' + +p.create_time() +# Expected output: 1267551141.5019531 + +p.cpu_times() +# Expected output: pcputimes(user=1.02, system=0.31, children_user=0.32, children_system=0.1, iowait=0.0) +``` + +---------------------------------------- + +TITLE: I/O Priority Constants (Windows) +DESCRIPTION: Constants representing I/O priority levels on Windows. These are used with psutil.Process.ionice() to get or set process I/O priority. Values include IOPRIO_VERYLOW, IOPRIO_LOW, IOPRIO_NORMAL, and IOPRIO_HIGH. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_88 + +LANGUAGE: python +CODE: +``` +import psutil + +process = psutil.Process(pid) +# Example: Set I/O priority to Normal +# process.ionice(psutil.IOPRIO_NORMAL) +# Example: Get I/O priority +# ioprio = process.ionice() + +``` + +---------------------------------------- + +TITLE: Run Tests (No Source Code / Production) +DESCRIPTION: Runs tests using Python's built-in unittest runner. This method is suitable for users who do not have the source code or when pytest is not installed. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/psutil/tests/README.rst#_snippet_1 + +LANGUAGE: python +CODE: +``` +python -m psutil.tests +``` + +---------------------------------------- + +TITLE: Get Virtual Memory Statistics +DESCRIPTION: Provides system memory usage statistics in bytes. Includes total physical memory, available memory (instantly usable by processes), and percentage usage. Available memory calculation varies by platform. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_9 + +LANGUAGE: python +CODE: +``` +>>> import psutil +>>> svmem = psutil.virtual_memory() +>>> svmem.total +17179869184 +>>> svmem.available +10000000000 +>>> svmem.percent +41.7 +``` + +---------------------------------------- + +TITLE: Platform Identification Constants +DESCRIPTION: Boolean constants indicating the current operating system. Only one of these will be True at a time. For example, on Windows, POSIX, LINUX, WINDOWS, MACOS, FREEBSD, NETBSD, OPENBSD, BSD, SUNOS, and AIX will be False, while WINDOWS will be True. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_84 + +LANGUAGE: python +CODE: +``` +import psutil + +if psutil.WINDOWS: + print("Running on Windows") +elif psutil.LINUX: + print("Running on Linux") +elif psutil.MACOS: + print("Running on macOS") +# ... and so on for other platforms +``` + +---------------------------------------- + +TITLE: Run Tests Without Pytest +DESCRIPTION: Enhancement for psutil version 6.1.0: Allows running tests via 'python3 -m psutil.tests' even if pytest is not installed. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_29 + +LANGUAGE: python +CODE: +``` +python3 -m psutil.tests +``` + +---------------------------------------- + +TITLE: Iterating Through Processes +DESCRIPTION: Demonstrates how to iterate through all running processes and retrieve specific information like PID and name. This is useful for process monitoring and management. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_35 + +LANGUAGE: python +CODE: +``` +import psutil + +for proc in psutil.process_iter(['pid', 'name']): + print(proc.info) +``` + +---------------------------------------- + +TITLE: setup.py Warnings Fix +DESCRIPTION: Addresses and resolves warnings generated during the setup.py build process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_227 + +LANGUAGE: python +CODE: +``` +# Original issue: fixed some setup.py warnings. +# This ensures a cleaner build process and adherence to packaging standards. +``` + +---------------------------------------- + +TITLE: Get CPU Times Utilization Percentage +DESCRIPTION: Provides CPU utilization percentages for specific CPU time categories (user, system, idle, etc.), similar to cpu_times(). Arguments interval and percpu have the same meaning as in cpu_percent(). The first call with interval=None returns 0.0. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_4 + +LANGUAGE: python +CODE: +``` +import psutil + +# Get system-wide CPU times utilization percentage +# print(psutil.cpu_times_percent()) + +# Get per-CPU times utilization percentage +# print(psutil.cpu_times_percent(percpu=True)) +``` + +---------------------------------------- + +TITLE: Network Connections +DESCRIPTION: Returns a list of network connections. The 'kind' parameter can be 'inet' (all internet connections), 'tcp', 'udp', 'unix'. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_15 + +LANGUAGE: python +CODE: +``` +psutil.net_connections(kind='tcp') +# Output: [sconn(fd=115, family=, type=, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED', pid=1254), sconn(fd=117, family=, type=, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING', pid=2987), ...] +``` + +---------------------------------------- + +TITLE: Process Management Functions +DESCRIPTION: This section details various functions for managing and querying process information. It includes functions for getting process IDs, priorities, resource limits, and exit codes, along with references to relevant Windows API calls and Python's os and resource modules. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_111 + +LANGUAGE: APIDOC +CODE: +``` +os.getpid() + - Returns the current process ID. + +os.getpriority(process_id) + - Returns the priority of a process. + - Parameters: + - process_id: The PID of the process. + +os.setpriority(process_id, priority) + - Sets the priority of a process. + - Parameters: + - process_id: The PID of the process. + - priority: The desired priority level. + +os.getresuid() + - Returns the real, effective, and saved set-user-IDs of the current process. + +os.getresgid() + - Returns the real, effective, and saved set-group-IDs of the current process. + +resource.getrlimit(resource_id) + - Returns the resource limits for a process. + - Parameters: + - resource_id: The resource identifier (e.g., RLIMIT_NOFILE). + - Returns: A tuple (soft_limit, hard_limit). + +resource.setrlimit(resource_id, limits) + - Sets the resource limits for a process. + - Parameters: + - resource_id: The resource identifier. + - limits: A tuple (soft_limit, hard_limit). + +subprocess.Popen.wait() + - Waits for a child process to terminate and returns its exit code. + +GetExitCodeProcess (Windows API) + - Retrieves the exit code of a specified process. + - Parameters: + - hProcess: A handle to the process. + - Returns: The exit code of the process. + +GetPriorityClass (Windows API) + - Retrieves the scheduling priority class of the specified process. + - Parameters: + - hProcess: A handle to the process. + - Returns: The priority class of the process. + +SetPriorityClass (Windows API) + - Sets the scheduling priority class of the specified process. + - Parameters: + - hProcess: A handle to the process. + - dwPriorityClass: The priority class to set. + +TerminateProcess (Windows API) + - Terminates a process and its threads. + - Parameters: + - hProcess: A handle to the process. + - uExitCode: The exit code for the process. + +``` + +LANGUAGE: python +CODE: +``` +import os +import resource +import subprocess + +# Get current process ID +pid = os.getpid() +print(f"Current PID: {pid}") + +# Get process priority (example for current process) +try: + priority = os.getpriority(pid) + print(f"Priority of PID {pid}: {priority}") + # Set priority (example, requires appropriate permissions) + # os.setpriority(pid, 10) # Set to a lower priority +except OSError as e: + print(f"Error getting/setting priority: {e}") + +# Get real, effective, and saved UIDs/GIDs +uid_info = os.getresuid() +print(f"UIDs (real, effective, saved): {uid_info}") +gid_info = os.getresgid() +print(f"GIDs (real, effective, saved): {gid_info}") + +# Get resource limits (e.g., open file descriptors) +try: + soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE) + print(f"Open file descriptor limits: soft={soft_limit}, hard={hard_limit}") + # Set resource limits (example, requires appropriate permissions) + # resource.setrlimit(resource.RLIMIT_NOFILE, (1024, 4096)) +except ValueError as e: + print(f"Error getting/setting resource limits: {e}") + +# Example of waiting for a subprocess (conceptual) +# try: +# process = subprocess.Popen(['sleep', '5']) +# exit_code = process.wait() +# print(f"Subprocess exited with code: {exit_code}") +# except FileNotFoundError: +# print("sleep command not found.") + +``` + +---------------------------------------- + +TITLE: Running psutil tests +DESCRIPTION: Command to execute the unit tests for the psutil library. This is useful for verifying the library's functionality and ensuring it works correctly in the current environment. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_102 + +LANGUAGE: bash +CODE: +``` +$ python3 -m psutil.tests +``` + +---------------------------------------- + +TITLE: I/O Priority Constants (Linux) +DESCRIPTION: Constants representing I/O priority classes on Linux. These are used with psutil.Process.ionice() to get or set process I/O priority. Values include IOPRIO_CLASS_NONE, IOPRIO_CLASS_RT, IOPRIO_CLASS_BE, and IOPRIO_CLASS_IDLE. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_87 + +LANGUAGE: python +CODE: +``` +import psutil + +process = psutil.Process(pid) +# Example: Set I/O priority to Best Effort +# process.ionice(psutil.IOPRIO_CLASS_BE) +# Example: Get I/O priority +# ioprio = process.ionice() + +``` + +---------------------------------------- + +TITLE: Get CPU Statistics +DESCRIPTION: Retrieves various CPU statistics since boot, including context switches, interrupts, software interrupts, and system calls. Software interrupts are always 0 on Windows and SunOS. System calls are always 0 on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_6 + +LANGUAGE: python +CODE: +``` +>>> import psutil +>>> psutil.cpu_stats() +scpustats(ctx_switches=20455687, interrupts=6598984, soft_interrupts=2134212, syscalls=0) +``` + +---------------------------------------- + +TITLE: Get CPU Frequency +DESCRIPTION: Returns current, minimum, and maximum CPU frequencies in MHz. On Linux, 'current' is real-time; on other platforms, it's a nominal fixed value. 'min' and 'max' are 0.0 if undetermined. 'percpu=True' returns frequencies for each CPU on supported systems (Linux, FreeBSD). Availability: Linux, macOS, Windows, FreeBSD, OpenBSD. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_7 + +LANGUAGE: python +CODE: +``` +>>> import psutil +>>> psutil.cpu_freq() +scpufreq(current=931.42925, min=800.0, max=3500.0) +>>> psutil.cpu_freq(percpu=True) +[scpufreq(current=2394.945, min=800.0, max=3500.0), + scpufreq(current=2236.812, min=800.0, max=3500.0), + scpufreq(current=1703.609, min=800.0, max=3500.0), + scpufreq(current=1754.289, min=800.0, max=3500.0)] +``` + +---------------------------------------- + +TITLE: List All Process IDs +DESCRIPTION: Returns a list of all PIDs currently running on the system. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_23 + +LANGUAGE: python +CODE: +``` +psutil.pids() +# Output: [1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224, 268, 1215, 1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355, 2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245, 4263, 4282, 4306, 4311, 4312, 4313, 4314, 4337, 4339, 4357, 4358, 4363, 4383, 4395, 4408, 4433, 4443, 4445, 4446, 5167, 5234, 5235, 5252, 5318, 5424, 5644, 6987, 7054, 7055, 7071] +``` + +---------------------------------------- + +TITLE: Process CPU Affinity +DESCRIPTION: Gets or sets the CPU affinity for a process, restricting it to specific CPUs. Accepts a list of CPU IDs. An empty list resets affinity to all eligible CPUs. Availability: Linux, Windows, FreeBSD. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_64 + +LANGUAGE: python +CODE: +``` +import psutil +psutil.cpu_count() +p = psutil.Process() +# get +print(p.cpu_affinity()) +# set; from now on, process will run on CPU #0 and #1 only +p.cpu_affinity([0, 1]) +print(p.cpu_affinity()) +# reset affinity against all eligible CPUs +p.cpu_affinity([]) +``` + +---------------------------------------- + +TITLE: psutil Project Status Badges +DESCRIPTION: This section displays various badges indicating the project's status, including downloads, GitHub stars, forks, contributors, build status for different platforms, test coverage, documentation status, latest version, supported Python versions, binary packages, and license. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_0 + +LANGUAGE: markdown +CODE: +``` +.. |downloads| image:: https://img.shields.io/pypi/dm/psutil.svg + :target: https://pepy.tech/project/psutil + :alt: Downloads + +.. |stars| image:: https://img.shields.io/github/stars/giampaolo/psutil.svg + :target: https://github.com/giampaolo/psutil/stargazers + :alt: Github stars + +.. |forks| image:: https://img.shields.io/github/forks/giampaolo/psutil.svg + :target: https://github.com/giampaolo/psutil/network/members + :alt: Github forks + +.. |contributors| image:: https://img.shields.io/github/contributors/giampaolo/psutil.svg + :target: https://github.com/giampaolo/psutil/graphs/contributors + :alt: Contributors + +.. |github-actions-wheels| image:: https://img.shields.io/github/actions/workflow/status/giampaolo/psutil/.github/workflows/build.yml.svg?label=Linux%2C%20macOS%2C%20Windows + :target: https://github.com/giampaolo/psutil/actions?query=workflow%3Abuild + :alt: Linux, macOS, Windows + +.. |github-actions-bsd| image:: https://img.shields.io/github/actions/workflow/status/giampaolo/psutil/.github/workflows/bsd.yml.svg?label=FreeBSD,%20NetBSD,%20OpenBSD + :target: https://github.com/giampaolo/psutil/actions?query=workflow%3Absd-tests + :alt: FreeBSD, NetBSD, OpenBSD + +.. |coverage| image:: https://coveralls.io/repos/github/giampaolo/psutil/badge.svg?branch=master + :target: https://coveralls.io/github/giampaolo/psutil?branch=master + :alt: Test coverage (coverall.io) + +.. |doc| image:: https://readthedocs.org/projects/psutil/badge/?version=latest + :target: https://psutil.readthedocs.io/en/latest/ + :alt: Documentation Status + +.. |version| image:: https://img.shields.io/pypi/v/psutil.svg?label=pypi + :target: https://pypi.org/project/psutil + :alt: Latest version + +.. |py-versions| image:: https://img.shields.io/pypi/pyversions/psutil.svg + :alt: Supported Python versions + +.. |packages| image:: https://repology.org/badge/tiny-repos/python:psutil.svg + :target: https://repology.org/metapackage/python:psutil/versions + :alt: Binary packages + +.. |license| image:: https://img.shields.io/pypi/l/psutil.svg + :target: https://github.com/giampaolo/psutil/blob/master/LICENSE + :alt: License + +.. |twitter| image:: https://img.shields.io/twitter/follow/grodola.svg?label=follow&style=flat&logo=twitter&logoColor=4FADFF + :target: https://twitter.com/grodola + :alt: Twitter Follow + +.. |tidelift| image:: https://tidelift.com/badges/github/giampaolo/psutil?style=flat + :target: https://tidelift.com/subscription/pkg/pypi-psutil?utm_source=pypi-psutil&utm_medium=referral&utm_campaign=readme + :alt: Tidelift +``` + +---------------------------------------- + +TITLE: Process Executable Path +DESCRIPTION: Gets the absolute path of the process executable. On some systems, if the executable cannot be determined for internal reasons (e.g., system process or path no longer exists), this may be an empty string. The return value is cached after the first call. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_38 + +LANGUAGE: APIDOC +CODE: +``` +exe() + Returns the process executable as an absolute path. + On some systems, if exe cannot be determined for some internal reason (e.g. system process or path no longer exists), this may be an empty string. + The return value is cached after first call. + Example: + >>> import psutil + >>> psutil.Process().exe() + '/usr/bin/python3' + Returns: The absolute path to the process executable. +``` + +---------------------------------------- + +TITLE: New Script: pstree.py +DESCRIPTION: Introduction of a new utility script, pstree.py, for visualizing process trees. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_405 + +LANGUAGE: python +CODE: +``` +# Enhancement: new pstree.py script. +# Implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: Process.cpu_affinity() Enhancement +DESCRIPTION: This snippet details the enhancement for `Process.cpu_affinity()` on Windows, allowing it to set CPU affinity beyond just CPU #0. It also notes the general addition of process CPU affinity (get and set) for Linux and Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_455 + +LANGUAGE: python +CODE: +``` +Process.cpu_affinity() # Set CPU affinity on Windows (previously limited to #0) +Process.cpu_affinity() # Get and set CPU affinity on Linux and Windows +``` + +---------------------------------------- + +TITLE: Process Threads and Context Switches +DESCRIPTION: Provides information about the threads running within the process, including their user and system times. It also reports the number of voluntary and involuntary context switches. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_30 + +LANGUAGE: python +CODE: +``` +p.threads() +# Expected output: [ +# pthread(id=5234, user_time=22.5, system_time=9.2891), +# pthread(id=5237, user_time=0.0707, system_time=1.1) +# ] + +p.num_threads() +# Expected output: 4 + +p.num_fds() +# Expected output: 8 + +p.num_ctx_switches() +# Expected output: pctxsw(voluntary=78, involuntary=19) +``` + +---------------------------------------- + +TITLE: Get CPU Count +DESCRIPTION: Returns the number of logical or physical CPUs in the system. Logical CPUs account for Hyper-Threading, while physical CPUs represent cores. Returns None if undetermined. On OpenBSD and NetBSD, physical CPU count is always None. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_5 + +LANGUAGE: python +CODE: +``` +>>> import psutil +>>> psutil.cpu_count() +4 +>>> psutil.cpu_count(logical=False) +2 +``` + +---------------------------------------- + +TITLE: Waiting for Processes to Terminate +DESCRIPTION: Illustrates how to wait for a list of processes to terminate, with an optional timeout and a callback function to execute when a process terminates. This is useful for managing process lifecycles. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_37 + +LANGUAGE: python +CODE: +``` +def on_terminate(proc): + print("process {} terminated".format(proc)) + +# waits for multiple processes to terminate +gone, alive = psutil.wait_procs(procs_list, timeout=3, callback=on_terminate) +``` + +---------------------------------------- + +TITLE: Network Interface Addresses +DESCRIPTION: Returns a dictionary mapping network interface names to a list of address information (IP, netmask, broadcast, etc.). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_16 + +LANGUAGE: python +CODE: +``` +psutil.net_if_addrs() +# Output: {'lo': [snicaddr(family=, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None), snicaddr(family=, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None), snicaddr(family=, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None)], 'wlan0': [snicaddr(family=, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None), snicaddr(family=, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None), snicaddr(family=, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]} +``` + +---------------------------------------- + +TITLE: Get CPU Utilization Percentage +DESCRIPTION: Returns system-wide CPU utilization as a percentage. When interval > 0.0, it's blocking and compares times before and after the interval. When interval is 0.0 or None, it compares times since the last call (non-blocking). The first call with interval=None returns 0.0. Can return per-CPU utilization when percpu=True. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_3 + +LANGUAGE: python +CODE: +``` +import psutil + +# Blocking call, waits for 1 second +print(psutil.cpu_percent(interval=1)) + +# Non-blocking call, returns utilization since last call +print(psutil.cpu_percent(interval=None)) + +# Blocking call, per-CPU utilization +# print(psutil.cpu_percent(interval=1, percpu=True)) +``` + +---------------------------------------- + +TITLE: dprint CLI Tool Introduction +DESCRIPTION: Enhancement for psutil version 7.0.1: Introduction of the 'dprint' CLI tool for formatting .yml and .md files. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_2 + +LANGUAGE: bash +CODE: +``` +dprint format .yml .md +``` + +---------------------------------------- + +TITLE: Swap Memory Information +DESCRIPTION: Returns a tuple with swap memory statistics including total, used, free, percent, sin (swap in), and sout (swap out). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_10 + +LANGUAGE: python +CODE: +``` +psutil.swap_memory() +# Output: sswap(total=2097147904, used=296128512, free=1801019392, percent=14.1, sin=304193536, sout=677842944) +``` + +---------------------------------------- + +TITLE: Get CPU Times +DESCRIPTION: Retrieves system CPU times as a named tuple. Attributes represent seconds spent in different CPU modes (user, system, idle, etc.). Availability of attributes varies by platform. Can return per-CPU times when percpu=True. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_2 + +LANGUAGE: python +CODE: +``` +import psutil + +# Get system-wide CPU times +print(psutil.cpu_times()) + +# Get per-CPU times +# print(psutil.cpu_times(percpu=True)) +``` + +---------------------------------------- + +TITLE: Disk Usage +DESCRIPTION: Returns a tuple with disk usage statistics for a given path, including total, used, free space, and percentage used. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_12 + +LANGUAGE: python +CODE: +``` +psutil.disk_usage('/') +# Output: sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5) +``` + +---------------------------------------- + +TITLE: Network Interface Statistics +DESCRIPTION: Returns a dictionary mapping network interface names to statistics like status (up/down), duplex, speed, MTU, and flags. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_17 + +LANGUAGE: python +CODE: +``` +psutil.net_if_stats() +# Output: {'lo': snicstats(isup=True, duplex=, speed=0, mtu=65536, flags='up,loopback,running'), 'wlan0': snicstats(isup=True, duplex=, speed=100, mtu=1500, flags='up,broadcast,running,multicast')} +``` + +---------------------------------------- + +TITLE: Process Parent PID +DESCRIPTION: Gets the parent process ID (PPID) of the current process. On Windows, the return value is cached after the first call. On POSIX systems, the PPID may change if the process becomes a zombie, so it's not cached. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_36 + +LANGUAGE: APIDOC +CODE: +``` +ppid() + Returns the process parent PID. + On Windows, the return value is cached after first call. + Not on POSIX because ppid may change if process becomes a zombie. + See also :meth:`parent` and :meth:`parents` methods. + Returns: The parent process ID. +``` + +---------------------------------------- + +TITLE: Process Resource Limits and Environment +DESCRIPTION: Manages process resource limits, such as the maximum number of open file descriptors. Also retrieves the process's environment variables as a dictionary. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_32 + +LANGUAGE: python +CODE: +``` +p.rlimit(psutil.RLIMIT_NOFILE, (5, 5)) # set resource limits (Linux only) + +p.rlimit(psutil.RLIMIT_NOFILE) +# Expected output: (5, 5) + +p.environ() +# Expected output: { +# 'LC_PAPER': 'it_IT.UTF-8', +# 'SHELL': '/bin/bash', +# 'GREP_OPTIONS': '--color=auto', +# 'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg', +# ... +# } +``` + +---------------------------------------- + +TITLE: Documentation Hosting Change +DESCRIPTION: Relocation of project documentation to readthedocs.com for better accessibility and features. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_403 + +LANGUAGE: text +CODE: +``` +# Enhancement: move documentation to readthedocs.com. +# Implemented in psutil version 2.0.0 +``` + +---------------------------------------- + +TITLE: CPU Times Percentage +DESCRIPTION: Returns system-wide CPU times as percentages. Can be calculated over an interval and for individual CPUs. Dependencies: None. Returns a named tuple or a list of named tuples. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_4 + +LANGUAGE: python +CODE: +``` +>>> for x in range(3): +... psutil.cpu_times_percent(interval=1, percpu=False) +... +scputimes(user=1.5, nice=0.0, system=0.5, idle=96.5, iowait=1.5, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0) +scputimes(user=1.0, nice=0.0, system=0.0, idle=99.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0) +scputimes(user=2.0, nice=0.0, system=0.0, idle=98.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0) +``` + +---------------------------------------- + +TITLE: System Resource Usage Methods +DESCRIPTION: This section covers methods for accessing system-wide resource usage, including CPU times, I/O counters, and memory information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_34 + +LANGUAGE: python +CODE: +``` +psutil.cpu_times() +psutil.io_counters() +psutil.memory_info() +psutil.memory_percent() +psutil.memory_maps() +``` + +---------------------------------------- + +TITLE: Checking Process Existence +DESCRIPTION: Shows how to check if a process with a given PID exists on the system. This is a fundamental check for process management. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_36 + +LANGUAGE: python +CODE: +``` +psutil.pid_exists(3) +``` + +---------------------------------------- + +TITLE: Process Open Files +DESCRIPTION: Retrieves a list of regular files opened by a process. Includes file path, descriptor, position, mode, and flags (Linux-specific). Note limitations on Windows and BSD. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_75 + +LANGUAGE: APIDOC +CODE: +``` +.. method:: open_files() + + Return regular files opened by process as a list of named tuples including + the following fields: + + - **path**: the absolute file name. + - **fd**: the file descriptor number; on Windows this is always ``-1``. + + Linux only: + + - **position** (*Linux*): the file (offset) position. + - **mode** (*Linux*): a string indicating how the file was opened, similarly + to `open`_ builtin ``mode`` argument. + Possible values are ``'r'``, ``'w'``, ``'a'``, ``'r+'`` and ``'a+'``. + There's no distinction between files opened in binary or text mode + (``"b"`` or ``"t"``). + - **flags** (*Linux*): the flags which were passed to the underlying + `os.open`_ C call when the file was opened (e.g. `os.O_RDONLY`_, + `os.O_TRUNC`_, etc). + + >>> import psutil + >>> p = psutil.Process() + >>> p.open_files() + [popenfile(path='/home/giampaolo/svn/psutil/file.ext', fd=3, position=0, mode='w', flags=32769)] + + .. warning:: + on Windows this method is not reliable due to some limitations of the + underlying Windows API which may hang when retrieving certain file + handles. + In order to work around that psutil spawns a thread to determine the file + handle name and kills it if it's not responding after 100ms. + That implies that this method on Windows is not guaranteed to enumerate + all regular file handles (see + `issue 597 `_). + Tools like ProcessHacker has the same limitation. + + .. warning:: + on BSD this method can return files with a null path ("" ) due to a + kernel bug, hence it's not reliable + (see `issue 595 `_). + + .. versionchanged:: + 3.1.0 no longer hangs on Windows. + + .. versionchanged:: + 4.1.0 new *position*, *mode* and *flags* fields on Linux. +``` + +---------------------------------------- + +TITLE: Disk I/O Counters +DESCRIPTION: Returns disk I/O statistics. If perdisk is True, it returns a dictionary of counters per disk. Otherwise, it returns a single tuple with aggregated counts. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_13 + +LANGUAGE: python +CODE: +``` +psutil.disk_io_counters(perdisk=False) +# Output: sdiskio(read_count=719566, write_count=1082197, read_bytes=18626220032, write_bytes=24081764352, read_time=5023392, write_time=63199568, read_merged_count=619166, write_merged_count=812396, busy_time=4523412) +``` + +---------------------------------------- + +TITLE: Virtual Memory Information +DESCRIPTION: Returns a tuple with virtual memory statistics including total, available, used, free, percent, active, inactive, buffers, cached, and shared memory. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_9 + +LANGUAGE: python +CODE: +``` +psutil.virtual_memory() +# Output: svmem(total=10367352832, available=6472179712, percent=37.6, used=8186245120, free=2181107712, active=4748992512, inactive=2758115328, buffers=790724608, cached=3500347392, shared=787554304) +``` + +---------------------------------------- + +TITLE: psutil Process.oneshot() Context Manager +DESCRIPTION: A utility context manager that significantly speeds up the retrieval of multiple process information by caching internal routine calls. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_32 + +LANGUAGE: APIDOC +CODE: +``` +.. method:: oneshot() + Utility context manager which considerably speeds up the retrieval of + multiple process information at the same time. + Internally different process info (e.g. :meth:`name`, :meth:`ppid`, + :meth:`uids`, :meth:`create_time`, ...) may be fetched by using the same + routine, but only one value is returned and the others are discarded. + When using this context manager the internal routine is executed once (in + the example below on :meth:`name()`) the value of interest is returned and + the others are cached. + The subsequent calls sharing the same internal routine will return the + cached value. + The cache is cleared when exiting the context manager block. + The advice is to use this every time you retrieve more than one information + about the process. If you're lucky, you'll get a hell of a speedup. + Example: + + >>> import psutil + >>> p = psutil.Process() + >>> with p.oneshot(): + ... p.name() # execute internal routine once collecting multiple info + ... p.cpu_times() # return cached value + ... p.cpu_percent() # return cached value + ... p.create_time() # return cached value + ... p.ppid() # return cached value + ... p.status() # return cached value + ... + >>> + + Here's a list of methods which can take advantage of the speedup depending + on what platform you're on. + In the table below horizontal empty rows indicate what process methods can + be efficiently grouped together internally. + The last column (speedup) shows an approximation of the speedup you can get + if you call all the methods together (best case scenario). + + +------------------------------+-------------------------------+------------------------------+------------------------------+--------------------------+--------------------------+ + | Linux | Windows | macOS | BSD | SunOS | AIX | + +==============================+===============================+==============================+==============================+==========================+==========================+ + | :meth:`cpu_num` | :meth:`~Process.cpu_percent` | :meth:`~Process.cpu_percent` | :meth:`cpu_num` | :meth:`name` | :meth:`name` | + +------------------------------+-------------------------------+------------------------------+------------------------------+--------------------------+--------------------------+ + | :meth:`~Process.cpu_percent` | :meth:`cpu_times` | :meth:`cpu_times` | :meth:`~Process.cpu_percent` | :meth:`cmdline` | :meth:`cmdline` | + +------------------------------+-------------------------------+------------------------------+------------------------------+--------------------------+--------------------------+ +``` + +---------------------------------------- + +TITLE: net_connections() and Process.connections() Exception Handling (NetBSD) +DESCRIPTION: Fixes a bug on NetBSD where net_connections() and Process.connections() could fail without raising an exception. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_315 + +LANGUAGE: python +CODE: +``` +from psutil import net_connections, Process + +try: + # Test net_connections() + net_connections() + # Test Process.connections() + p = Process() + p.connections() +except Exception as e: + print(f"An error occurred: {e}") +``` + +---------------------------------------- + +TITLE: New Script: ps.py +DESCRIPTION: Introduction of a new utility script, ps.py, likely for process information display. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_407 + +LANGUAGE: python +CODE: +``` +# Enhancement: add ps.py script. +# Implemented in psutil version 2.1.2 +``` + +---------------------------------------- + +TITLE: Sensor Temperatures +DESCRIPTION: Returns a dictionary of hardware temperatures, typically for CPUs and other components. Includes current, high, and critical temperature thresholds. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_18 + +LANGUAGE: python +CODE: +``` +psutil.sensors_temperatures() +# Output: {'acpitz': [shwtemp(label='', current=47.0, high=103.0, critical=103.0)], 'asus': [shwtemp(label='', current=47.0, high=None, critical=None)], '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)]} +``` + +---------------------------------------- + +TITLE: Process Parent and Children +DESCRIPTION: Retrieves the parent process ID (PPID), the parent Process object, and a list of all child processes, optionally recursively. Useful for understanding process hierarchy. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_25 + +LANGUAGE: python +CODE: +``` +p.ppid() +# Expected output: 7054 + +p.parent() +# Expected output: psutil.Process(pid=4699, name='bash', status='sleeping', started='09:06:44') + +p.parents() +# Expected output: [ +# psutil.Process(pid=4699, name='bash', started='09:06:44'), +# psutil.Process(pid=4689, name='gnome-terminal-server', status='sleeping', started='0:06:44'), +# psutil.Process(pid=1, name='systemd', status='sleeping', started='05:56:55') +# ] + +p.children(recursive=True) +# Expected output: [ +# psutil.Process(pid=29835, name='python3', status='sleeping', started='11:45:38'), +# psutil.Process(pid=29836, name='python3', status='waking', started='11:43:39') +# ] +``` + +---------------------------------------- + +TITLE: Process.rlimit() FreeBSD Support +DESCRIPTION: Adds support for Process.rlimit() on FreeBSD. This enhancement allows retrieving and setting resource limits for processes on FreeBSD systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_91 + +LANGUAGE: APIDOC +CODE: +``` +Process.rlimit() + - Added support for FreeBSD. +``` + +---------------------------------------- + +TITLE: psutil API Reference +DESCRIPTION: This section provides a reference for key psutil functions and their parameters. It includes details on CPU, disk, and process-related operations. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_557 + +LANGUAGE: APIDOC +CODE: +``` +PROCFS_PATH: Path to the proc filesystem (Linux). + +boot_time(): Return the system boot time expressed in seconds since the Epoch. + +cpu_count(logical=True): Return the number of logical CPUs in the system. If logical is False return physical cores only. + +cpu_freq(percpu=False): Return a tuple of logical CPUs core frequencies. If percpu is True return a list of frequencies for each logical CPU. + +cpu_percent(interval=None, percpu=False): + Return the system-wide CPU utilization as a percentage. + If interval is None return immediately. If interval is a number, block for that many seconds and return the percentage. + If percpu is True return a list of percentages for each logical CPU. + +cpu_stats(): Return a tuple of system-wide CPU statistics: + (user, system, idle, iowait, ...) + +cpu_times(percpu=False): + Return a tuple of system-wide CPU times: + (user, system, idle, ...) + If percpu is True return a list of tuples for each logical CPU. + +cpu_times_percent(interval=None, percpu=False): + Return system-wide CPU times percentages. + If interval is None return immediately. If interval is a number, block for that many seconds and return the percentages. + If percpu is True return a list of percentages for each logical CPU. + +disk_io_counters(perdisk=False, nowrap=True): + Return system disk I/O statistics. + If perdisk is True return a dictionary keyed by disk device name. + If nowrap is True return None for counters that have no value or are not supported. + +disk_partitions(all=False): + Return a list of disk partitions. + If all is True return all partitions, including cdrom. + +Process.open_files(): Return a list of open files for this process. + +Process.connections(kind='inet'): + Return a list of network connections for this process. + kind can be 'inet' (default), 'tcp', 'udp', 'unix'. + +Process.send_signal(signal): + Send a signal to the process. + +Process.terminate(): + Send SIGTERM to the process. + +Process.ppid(): Return process parent PID. + +Process.uids(): Return a tuple of (real, effective, saved) UIDs. + +Process.gids(): Return a tuple of (real, effective, saved) GIDs. + +Process.name(): Return process name. + +Process.exe(): Return the process executable path. + +Process.cmdline(): Return the process command line as a list of strings. + +Process.create_time(): Return the process creation time expressed in seconds since the Epoch. + +Process.cwd(): Return the process current working directory path. + +Process.is_running(): Return True if process is running, False otherwise. + +Process.suspend(): Suspend process execution. + +Process.resume(): Resume process execution. + +Process.kill(): Kill the process. + +pid_exists(pid): + Return True if PID exists in the system, False otherwise. + +NoSuchProcess: Exception raised when a process does not exist. + +AccessDenied: Exception raised when access is denied to a process. + +``` + +---------------------------------------- + +TITLE: Compatibility Notes +DESCRIPTION: Information regarding compatibility changes, specifically the discontinuation of .exe files on PyPI for Windows and the implications for users. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_219 + +LANGUAGE: text +CODE: +``` +Compatibility Notes: +- `.exe` files for Windows are no longer uploaded on PyPI as per PEP-527. Only wheels are provided. +``` + +---------------------------------------- + +TITLE: CPU Utilization Percentage +DESCRIPTION: Returns the system-wide CPU utilization as a percentage. Can be calculated over an interval and for individual CPUs. Dependencies: None. Returns a float or a list of floats. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_3 + +LANGUAGE: python +CODE: +``` +>>> for x in range(3): +... psutil.cpu_percent(interval=1) +... +4.0 +5.9 +3.8 +>>> +>>> for x in range(3): +... psutil.cpu_percent(interval=1, percpu=True) +... +[4.0, 6.9, 3.7, 9.2] +[7.0, 8.5, 2.4, 2.1] +[1.2, 9.0, 9.9, 7.2] +``` + +---------------------------------------- + +TITLE: Makefile for Tasks +DESCRIPTION: Introduction of a Makefile to streamline repetitive tasks such as running tests, including on Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_402 + +LANGUAGE: makefile +CODE: +``` +# Enhancement: add a Makefile for running tests and other repetitive tasks (also on Windows). +# Implemented in psutil version 2.0.0 +``` + +---------------------------------------- + +TITLE: psutil Process Methods API +DESCRIPTION: Provides an overview of psutil's process management methods, including their parameters, return values, availability, and version changes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_61 + +LANGUAGE: APIDOC +CODE: +``` +Process: + ionice(class_or_priority=None, value=None): + Get or set process I/O priority. + On Linux: class_or_priority can be IOPRIO_CLASS_NONE, IOPRIO_CLASS_BE, IOPRIO_CLASS_IDLE, IOPRIO_CLASS_RT. + value is an integer from 0 to 7. + On Windows: class_or_priority can be IOPRIO_IDLE, IOPRIO_NORMAL, IOPRIO_HIGH, IOPRIO_VERYHIGH. + Availability: Linux, Windows Vista+. + Example: + p.ionice(psutil.IOPRIO_CLASS_RT, value=7) # Linux + p.ionice(psutil.IOPRIO_HIGH) # Windows + + rlimit(resource, limits=None): + Get or set process resource limits. + resource: One of psutil.RLIMIT_* constants. + limits: A (soft, hard) tuple. Values can be integers or psutil.RLIM_INFINITY. + Returns: A (soft, hard) tuple for get operations. + Availability: Linux, FreeBSD. + Example: + p.rlimit(psutil.RLIMIT_NOFILE, (128, 128)) + p.rlimit(psutil.RLIMIT_FSIZE) + + io_counters(): + Return process I/O statistics as a named tuple. + Fields include read_count, write_count, read_bytes, write_bytes. + Linux specific: read_chars, write_chars. + Windows specific: other_count, other_bytes. + Availability: Linux, BSD, Windows, AIX. + Example: + p.io_counters() + + num_ctx_switches(): + Return the number of voluntary and involuntary context switches (cumulative). + Availability: All platforms except OpenBSD. + + num_fds(): + Return the number of file descriptors currently opened by this process (non-cumulative). + Availability: UNIX. + + num_handles(): + Return the number of handles currently used by this process (non-cumulative). + Availability: Windows. + + num_threads(): + Return the number of threads currently used by this process (non-cumulative). + + threads(): + Return threads opened by process as a list of named tuples. + Each tuple contains: id, user_time, system_time. + Requires root privileges on OpenBSD. + + cpu_times(): + Return a named tuple representing the accumulated process times in seconds. + Fields: user, system. +``` + +---------------------------------------- + +TITLE: CPU Count +DESCRIPTION: Returns the number of logical or physical CPUs. Dependencies: None. Returns an integer. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_5 + +LANGUAGE: python +CODE: +``` +>>> psutil.cpu_count() +4 +>>> psutil.cpu_count(logical=False) +2 +``` + +---------------------------------------- + +TITLE: Process Information Retrieval (as_dict) +DESCRIPTION: Retrieves process information as a dictionary. The `as_dict` method allows fetching specific attributes or all available attributes. It uses an internal `oneshot` context manager for efficiency. Exceptions like `AccessDenied` or `ZombieProcess` may be raised. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_44 + +LANGUAGE: python +CODE: +``` +import psutil + +p = psutil.Process() +# Get specific attributes +print(p.as_dict(attrs=['pid', 'name', 'username'])) +# Get all attributes +print(list(psutil.Process().as_dict().keys())) +``` + +---------------------------------------- + +TITLE: psutil WindowsService Class Methods +DESCRIPTION: Documents the attributes and methods of the psutil.WindowsService class, used to represent and manage Windows services. Covers retrieving service name, display name, binary path, user, status, and description. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_82 + +LANGUAGE: APIDOC +CODE: +``` +psutil.WindowsService(name) + Represents a Windows service. + + name(): + The service name. + + display_name(): + The service display name. + + binpath(): + The path to the service binary. + + username(): + The name of the user that owns the service. + + start_type(): + The service start type ('automatic', 'manual', 'disabled'). + + pid(): + The process PID of the service, or None if not running. + + status(): + The current status of the service ('running', 'stopped', etc.). + + description(): + The service's long description. + + as_dict(): + Returns all service information as a dictionary. + + Availability: Windows + + Example: + >>> s = psutil.win_service_get('alg') + >>> s.status() + 'stopped' +``` + +---------------------------------------- + +TITLE: Python Built-in Functions and Types +DESCRIPTION: This section lists several Python built-in functions and types that are relevant to process and system operations, including `hash`, `open`, and `set`. It provides links to the Python documentation for each. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_117 + +LANGUAGE: APIDOC +CODE: +``` +hash(object) + - Return the hash value of the object. + - References: https://docs.python.org/3/library/functions.html#hash + +open(file, mode='r', ...) + - Open a file and return a corresponding file object. + - References: https://docs.python.org/3/library/functions.html#open + +set + - Represents an unordered collection of unique elements. + - References: https://docs.python.org/3/library/stdtypes.html#types-set. + +``` + +---------------------------------------- + +TITLE: Disk Partitions +DESCRIPTION: Returns a list of mounted disk partitions. The 'all' parameter (default False) attempts to return only physical devices, ignoring pseudo or memory filesystems. Note that this behavior might vary across systems (e.g., 'all' is ignored on BSD). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_12 + +LANGUAGE: APIDOC +CODE: +``` +disk_partitions(all=False) + Returns a list of named tuples representing mounted disk partitions. + Parameters: + - all (bool): If True, return all partitions, including pseudo, memory, duplicate, and inaccessible ones. Defaults to False (physical devices only). + Returns: + A list of sdiskpart named tuples with the following fields: + - device: The device path (e.g., '/dev/sda3'). On Windows, the drive letter (e.g., 'C:\\'). + - mountpoint: The mount point path (e.g., '/'). On Windows, the drive letter (e.g., 'C:\\'). + - fstype: The partition filesystem type (e.g., 'ext4', 'NTFS'). + - opts: A comma-separated string of mount options. + Example: + >>> import psutil + >>> psutil.disk_partitions() + [sdiskpart(device='/dev/sda3', mountpoint='/', fstype='ext4', opts='rw,errors=remount-ro'), + sdiskpart(device='/dev/sda7', mountpoint='/home', fstype='ext4', opts='rw')] +``` + +---------------------------------------- + +TITLE: psutil Process Methods +DESCRIPTION: This section details various methods available for interacting with processes using the psutil library. It covers methods for retrieving parent processes, process IDs, signal handling, and process state. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_562 + +LANGUAGE: APIDOC +CODE: +``` +Process.parents() + - Returns a list of parent Process instances. + +Process.pid + - Returns the process ID (PID) of the process. + +Process.ppid() + - Returns the parent process ID (PPID) of the process. + +Process.resume() + - Resumes a suspended process. + +Process.rlimit(resource, soft=None, hard=None) + - Get or set resource limits for a process. + - Parameters: + - resource: The resource to query or set (e.g., RLIMIT_CPU). + - soft: The soft limit value. + - hard: The hard limit value. + - Returns: A tuple of (soft, hard) limits. + +Process.send_signal(signal) + - Sends a signal to the process. + - Parameters: + - signal: The signal to send (e.g., SIGTERM). + +Process.status() + - Returns the process status as a string (e.g., 'running', 'sleeping'). + +Process.suspend() + - Suspends a process. + +Process.terminal() + - Returns the controlling terminal of the process. + +Process.terminate() + - Terminates the process. + +Process.threads() + - Returns a list of Thread instances representing the threads of the process. + +Process.uids() + - Returns a tuple of (real, effective, saved) user IDs. + +Process.username() + - Returns the username of the process owner. + +Process.wait(timeout=None) + - Waits for the process to terminate. + - Parameters: + - timeout: Optional timeout in seconds. +``` + +---------------------------------------- + +TITLE: Process I/O and Network Activity +DESCRIPTION: Retrieves I/O statistics such as read/write counts and bytes. Also lists open files associated with the process and its network connections, including local and remote addresses and status. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_29 + +LANGUAGE: python +CODE: +``` +p.io_counters() +# Expected output: pio(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632, read_chars=456232, write_chars=517543) + +p.open_files() +# Expected output: [ +# popenfile(path='/home/giampaolo/monit.py', fd=3, position=0, mode='r', flags=32768), +# popenfile(path='/var/log/monit.log', fd=4, position=235542, mode='a', flags=33793) +# ] + +p.net_connections(kind='tcp') +# Expected output: [ +# pconn(fd=115, family=, type=, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED'), +# pconn(fd=117, family=, type=, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING') +# ] +``` + +---------------------------------------- + +TITLE: System Statistics and Information +DESCRIPTION: This section covers functions and scripts related to system-level statistics, including file system statistics, I/O statistics, memory usage, and network information. It references man pages, kernel documentation, and specific Python scripts provided with psutil. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_112 + +LANGUAGE: APIDOC +CODE: +``` +getfsstat() + - Returns file system statistics. + - References: http://www.manpagez.com/man/2/getfsstat/ + +ioprio_get() + - Gets I/O scheduling class and priority. + - References: https://linux.die.net/man/2/ioprio_get + - Related: iostats doc (https://www.kernel.org/doc/Documentation/iostats.txt) + +shutil.disk_usage(path) + - Returns disk usage statistics for a given path. + - Parameters: + - path: The directory or file path. + - Returns: A tuple (total, used, free) in bytes. + +Scripts: + - ifconfig.py: Network interface configuration. + - iotop.py: I/O usage monitoring. + - meminfo.py: Memory usage details. + - netstat.py: Network statistics. + - nettop.py: Network monitoring. + - pmap.py: Process memory map. + - procinfo.py: Process information. + - procsmem.py: Process memory usage. + - sensors.py: Hardware sensor readings. + - temperatures.py: Temperature sensor readings. + +``` + +LANGUAGE: python +CODE: +``` +import shutil +import os + +# Get disk usage for the current directory +try: + usage = shutil.disk_usage('.') + print(f"Disk Usage:") + print(f" Total: {usage.total} bytes") + print(f" Used: {usage.used} bytes") + print(f" Free: {usage.free} bytes") +except OSError as e: + print(f"Error getting disk usage: {e}") + +# Conceptual usage of getfsstat and ioprio_get would involve psutil library calls +# import psutil +# fs_stats = psutil.disk_io_counters(perdisk=True) +# print(fs_stats) +# io_priority = psutil.Process().ionice() +# print(f"I/O Priority: {io_priority}") + +``` + +---------------------------------------- + +TITLE: CPU Statistics +DESCRIPTION: Retrieves CPU statistics including context switches, interrupts, and system calls. Dependencies: None. Returns a named tuple. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_6 + +LANGUAGE: python +CODE: +``` +>>> psutil.cpu_stats() +scpustats(ctx_switches=20455687, interrupts=6598984, soft_interrupts=2134212, syscalls=0) +``` + +---------------------------------------- + +TITLE: Process.environ() Exception Handling (Windows) +DESCRIPTION: Improves exception handling for Process.environ() on Windows when querying 64-bit processes in 32-bit-WoW mode, now raising AccessDenied. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_167 + +LANGUAGE: python +CODE: +``` +Process.environ() +``` + +---------------------------------------- + +TITLE: psutil Version History +DESCRIPTION: This section details the release history of the psutil library. It includes version numbers, release dates, and links to the PyPI download page, the 'what's new' changelog, and the code diff for each version. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_108 + +LANGUAGE: text +CODE: +``` +5.1.3 - 2017-02-03: + PyPI: https://pypi.org/project/psutil/5.1.3/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#513 + Diff: https://github.com/giampaolo/psutil/compare/release-5.1.2...release-5.1.3#files_bucket + +5.1.2 - 2017-02-03: + PyPI: https://pypi.org/project/psutil/5.1.2/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#512 + Diff: https://github.com/giampaolo/psutil/compare/release-5.1.1...release-5.1.2#files_bucket + +5.1.1 - 2017-02-03: + PyPI: https://pypi.org/project/psutil/5.1.1/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#511 + Diff: https://github.com/giampaolo/psutil/compare/release-5.1.0...release-5.1.1#files_bucket + +5.1.0 - 2017-02-01: + PyPI: https://pypi.org/project/psutil/5.1.0/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#510 + Diff: https://github.com/giampaolo/psutil/compare/release-5.0.1...release-5.1.0#files_bucket + +5.0.1 - 2016-12-21: + PyPI: https://pypi.org/project/psutil/5.0.1/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#501 + Diff: https://github.com/giampaolo/psutil/compare/release-5.0.0...release-5.0.1#files_bucket + +5.0.0 - 2016-11-06: + PyPI: https://pypi.org/project/psutil/5.0.0/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#500 + Diff: https://github.com/giampaolo/psutil/compare/release-4.4.2...release-5.0.0#files_bucket + +4.4.2 - 2016-10-05: + PyPI: https://pypi.org/project/psutil/4.4.2/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#442 + Diff: https://github.com/giampaolo/psutil/compare/release-4.4.1...release-4.4.2#files_bucket + +4.4.1 - 2016-10-25: + PyPI: https://pypi.org/project/psutil/4.4.1/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#441 + Diff: https://github.com/giampaolo/psutil/compare/release-4.4.0...release-4.4.1#files_bucket + +4.4.0 - 2016-10-23: + PyPI: https://pypi.org/project/psutil/4.4.0/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#440 + Diff: https://github.com/giampaolo/psutil/compare/release-4.3.1...release-4.4.0#files_bucket + +4.3.1 - 2016-09-01: + PyPI: https://pypi.org/project/psutil/4.3.1/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#431 + Diff: https://github.com/giampaolo/psutil/compare/release-4.3.0...release-4.3.1#files_bucket + +4.3.0 - 2016-06-18: + PyPI: https://pypi.org/project/psutil/4.3.0/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#430 + Diff: https://github.com/giampaolo/psutil/compare/release-4.2.0...release-4.3.0#files_bucket + +4.2.0 - 2016-05-14: + PyPI: https://pypi.org/project/psutil/4.2.0/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#420 + Diff: https://github.com/giampaolo/psutil/compare/release-4.1.0...release-4.2.0#files_bucket + +4.1.0 - 2016-03-12: + PyPI: https://pypi.org/project/psutil/4.1.0/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#410 + Diff: https://github.com/giampaolo/psutil/compare/release-4.0.0...release-4.1.0#files_bucket + +4.0.0 - 2016-02-17: + PyPI: https://pypi.org/project/psutil/4.0.0/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#400 + Diff: https://github.com/giampaolo/psutil/compare/release-3.4.2...release-4.0.0#files_bucket + +3.4.2 - 2016-01-20: + PyPI: https://pypi.org/project/psutil/3.4.2/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#342 + Diff: https://github.com/giampaolo/psutil/compare/release-3.4.1...release-3.4.2#files_bucket + +3.4.1 - 2016-01-15: + PyPI: https://pypi.org/project/psutil/3.4.1/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#341 + Diff: https://github.com/giampaolo/psutil/compare/release-3.3.0...release-3.4.1#files_bucket + +3.3.0 - 2015-11-25: + PyPI: https://pypi.org/project/psutil/3.3.0/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#330 + Diff: https://github.com/giampaolo/psutil/compare/release-3.2.2...release-3.3.0#files_bucket + +3.2.2 - 2015-10-04: + PyPI: https://pypi.org/project/psutil/3.2.2/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#322 + Diff: https://github.com/giampaolo/psutil/compare/release-3.2.1...release-3.2.2#files_bucket + +3.2.1 - 2015-09-03: + PyPI: https://pypi.org/project/psutil/3.2.1/#files + What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#321 + Diff: https://github.com/giampaolo/psutil/compare/release-3.2.0...release-3.2.1#files_bucket +``` + +---------------------------------------- + +TITLE: CPU and System Load +DESCRIPTION: This section focuses on retrieving CPU-related information, including the number of CPU cores and system load averages. It references Python's os module for these functionalities. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_113 + +LANGUAGE: APIDOC +CODE: +``` +os.cpu_count() + - Returns the number of CPUs in the system. + - Returns: An integer representing the number of CPUs, or None if undetermined. + +os.getloadavg() + - Returns the system load average for the last 1, 5, and 15 minutes. + - Returns: A tuple of three floats (loadavg1, loadavg5, loadavg15). + - Note: Only available on Unix-like systems. + +``` + +LANGUAGE: python +CODE: +``` +import os + +# Get the number of CPU cores +cpu_cores = os.cpu_count() +if cpu_cores: + print(f"Number of CPU cores: {cpu_cores}") +else: + print("Could not determine the number of CPU cores.") + +# Get system load average (Unix-like systems only) +try: + load_avg = os.getloadavg() + print(f"System Load Average (1m, 5m, 15m): {load_avg}") +except AttributeError: + print("os.getloadavg() is not available on this system.") +except OSError as e: + print(f"Error getting load average: {e}") + +``` + +---------------------------------------- + +TITLE: WindowsService.description() Error Handling +DESCRIPTION: Bug fix for psutil version 7.0.1: WindowsService.description() now returns an empty string instead of failing with ERROR_NOT_FOUND. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_15 + +LANGUAGE: python +CODE: +``` +from psutil import WindowsService + +# Example usage +# try: +# service = WindowsService('ServiceName') +# desc = service.description() +# print(f"Description: {desc}") +# except Exception as e: +# print(f"Error getting description: {e}") +``` + +---------------------------------------- + +TITLE: Process.open_files() Rewrite on FreeBSD +DESCRIPTION: Process.open_files() on FreeBSD has been rewritten in C and no longer relies on the external 'lsof' command, improving performance and reliability. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_479 + +LANGUAGE: python +CODE: +``` +# Process.open_files() rewritten in C for FreeBSD. +``` + +---------------------------------------- + +TITLE: MidnightBSD Support Added +DESCRIPTION: Introduces support for MidnightBSD, expanding the range of supported operating systems for the psutil library. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_67 + +LANGUAGE: python +CODE: +``` +# Example of using psutil on MidnightBSD (functionality should be similar) +# import psutil +# print(f"CPU Times: {psutil.cpu_times()}") +# print(f"Disk Partitions: {psutil.disk_partitions()}") +``` + +---------------------------------------- + +TITLE: Network I/O Counters +DESCRIPTION: Returns network I/O statistics. If pernic is True, it returns a dictionary of counters per network interface. Otherwise, it returns a single tuple with aggregated counts. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_14 + +LANGUAGE: python +CODE: +``` +psutil.net_io_counters(pernic=True) +# Output: {'eth0': netio(bytes_sent=485291293, bytes_recv=6004858642, packets_sent=3251564, packets_recv=4787798, errin=0, errout=0, dropin=0, dropout=0), 'lo': netio(bytes_sent=2838627, bytes_recv=2838627, packets_sent=30567, packets_recv=30567, errin=0, errout=0, dropin=0, dropout=0)} +``` + +---------------------------------------- + +TITLE: ValueError for Negative cpu_percent() Input +DESCRIPTION: No description + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_320 + + + +---------------------------------------- + +TITLE: Sensor Fan Speeds +DESCRIPTION: Returns a dictionary of fan speeds, typically for CPU fans. Includes the fan label and current speed in RPM. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_19 + +LANGUAGE: python +CODE: +``` +psutil.sensors_fans() +# Output: {'asus': [sfan(label='cpu_fan', current=3200)]} +``` + +---------------------------------------- + +TITLE: Run a Specific Test +DESCRIPTION: Allows running a single, specific test case by providing its path as an argument to the make test command. Requires the source code. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/psutil/tests/README.rst#_snippet_3 + +LANGUAGE: bash +CODE: +``` +make test ARGS=psutil.tests.test_system.TestDiskAPIs +``` + +---------------------------------------- + +TITLE: Process Information Methods +DESCRIPTION: This section details various methods available for retrieving information about a process, such as its name, PID, status, and associated user and group IDs. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_33 + +LANGUAGE: python +CODE: +``` +psutil.Process.name() +psutil.Process.ppid() +psutil.Process.status() +psutil.Process.gids() +psutil.Process.uids() +psutil.Process.username() +psutil.Process.terminal() +psutil.Process.exe() +psutil.Process.create_time() +psutil.Process.num_ctx_switches() +psutil.Process.num_threads() +psutil.Process.num_handles() +``` + +---------------------------------------- + +TITLE: psutil Version History and Release Notes +DESCRIPTION: This section details the release history of the psutil library. It provides links to download specific versions from PyPI, view detailed changelogs ('what's new'), and compare code differences between consecutive releases on GitHub. This information is crucial for tracking library updates and understanding changes across versions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_106 + +LANGUAGE: python +CODE: +``` +5.9.8 - 2023-12-17 + - PyPI: https://pypi.org/project/psutil/5.9.8/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#598 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.9.7...release-5.9.8#files_bucket + +5.9.7 - 2023-10-15 + - PyPI: https://pypi.org/project/psutil/5.9.7/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#597 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.9.6...release-5.9.7#files_bucket + +5.9.6 - 2023-04-17 + - PyPI: https://pypi.org/project/psutil/5.9.6/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#596 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.9.5...release-5.9.6#files_bucket + +5.9.5 - 2022-11-07 + - PyPI: https://pypi.org/project/psutil/5.9.5/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#595 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.9.4...release-5.9.5#files_bucket + +5.9.4 - 2022-10-18 + - PyPI: https://pypi.org/project/psutil/5.9.4/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#594 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.9.3...release-5.9.4#files_bucket + +5.9.3 - 2022-09-04 + - PyPI: https://pypi.org/project/psutil/5.9.3/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#593 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.9.2...release-5.9.3#files_bucket + +5.9.2 - 2022-05-20 + - PyPI: https://pypi.org/project/psutil/5.9.2/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#592 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.9.1...release-5.9.2#files_bucket + +5.9.1 - 2021-12-29 + - PyPI: https://pypi.org/project/psutil/5.9.1/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#591 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.9.0...release-5.9.1#files_bucket + +5.9.0 - 2020-12-19 + - PyPI: https://pypi.org/project/psutil/5.9.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#590 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.8.0...release-5.9.0#files_bucket + +5.8.0 - 2020-10-24 + - PyPI: https://pypi.org/project/psutil/5.8.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#580 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.7.3...release-5.8.0#files_bucket + +5.7.3 - 2020-07-15 + - PyPI: https://pypi.org/project/psutil/5.7.3/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#573 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.7.2...release-5.7.3#files_bucket + +5.7.2 - 2020-07-15 + - PyPI: https://pypi.org/project/psutil/5.7.2/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#572 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.7.1...release-5.7.2#files_bucket + +5.7.1 - 2020-02-18 + - PyPI: https://pypi.org/project/psutil/5.7.1/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#571 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.7.0...release-5.7.1#files_bucket + +5.7.0 - 2019-11-26 + - PyPI: https://pypi.org/project/psutil/5.7.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#570 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.6.7...release-5.7.0#files_bucket + +5.6.7 - 2019-11-25 + - PyPI: https://pypi.org/project/psutil/5.6.7/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#567 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.6.6...release-5.6.7#files_bucket + +5.6.6 - 2019-11-06 + - PyPI: https://pypi.org/project/psutil/5.6.6/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#566 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.6.5...release-5.6.6#files_bucket + +5.6.5 - 2019-11-04 + - PyPI: https://pypi.org/project/psutil/5.6.5/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#565 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.6.4...release-5.6.5#files_bucket + +5.6.4 - 2019-06-11 + - PyPI: https://pypi.org/project/psutil/5.6.4/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#564 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.6.3...release-5.6.4#files_bucket + +5.6.3 - 2019-04-26 + - PyPI: https://pypi.org/project/psutil/5.6.3/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#563 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.6.2...release-5.6.3#files_bucket +``` + +---------------------------------------- + +TITLE: psutil Debug Mode Link +DESCRIPTION: Provides a direct link to the psutil documentation for enabling debug mode, which is recommended when reporting malfunctions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/CONTRIBUTING.md#_snippet_0 + +LANGUAGE: markdown +CODE: +``` +[debug mode](https://psutil.readthedocs.io/en/latest/#debug-mode) +``` + +---------------------------------------- + +TITLE: Process Memory Information +DESCRIPTION: Retrieves detailed memory usage information, including Resident Set Size (RSS) and Virtual Memory Size (VMS). `memory_full_info` provides more granular details like Unique Set Size (USS) on supported platforms. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_28 + +LANGUAGE: python +CODE: +``` +p.memory_info() +# Expected output: pmem(rss=10915840, vms=67608576, shared=3313664, text=2310144, lib=0, data=7262208, dirty=0) + +p.memory_full_info() # "real" USS memory usage (Linux, macOS, Win only) +# Expected output: pfullmem(rss=10199040, vms=52133888, shared=3887104, text=2867200, lib=0, data=5967872, dirty=0, uss=6545408, pss=6872064, swap=0) + +p.memory_percent() +# Expected output: 0.7823 + +p.memory_maps() +# Expected output: [ +# pmmap_grouped(path='/lib/x8664-linux-gnu/libutil-2.15.so', rss=32768, size=2125824, pss=32768, shared_clean=0, shared_dirty=0, private_clean=20480, private_dirty=12288, referenced=32768, anonymous=12288, swap=0), +# pmmap_grouped(path='/lib/x8664-linux-gnu/libc-2.15.so', rss=3821568, size=3842048, pss=3821568, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=3821568, referenced=3575808, anonymous=3821568, swap=0), +# pmmap_grouped(path='[heap]', rss=32768, size=139264, pss=32768, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=32768, referenced=32768, anonymous=32768, swap=0), +# pmmap_grouped(path='[stack]', rss=2465792, size=2494464, pss=2465792, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=2465792, referenced=2277376, anonymous=2465792, swap=0), +# ... +# ] +``` + +---------------------------------------- + +TITLE: Enabling psutil Debug Mode on UNIX +DESCRIPTION: Demonstrates how to enable debug mode for psutil on UNIX-like systems by setting the PSUTIL_DEBUG environment variable. This can provide additional information for debugging issues. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_103 + +LANGUAGE: bash +CODE: +``` +$ PSUTIL_DEBUG=1 python3 script.py +psutil-debug [psutil/_psutil_linux.c:150]> setmntent() failed (ignored) +``` + +---------------------------------------- + +TITLE: psutil Version History +DESCRIPTION: This section lists the release history of the psutil library. Each entry includes the version number, release date, and links to download the release from PyPI, view the changelog, and see the code differences between versions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_110 + +LANGUAGE: text +CODE: +``` +0.7.1 - 2013-04-12 + - PyPI: https://pypi.org/project/psutil/0.7.1/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#071 + - Diff: https://github.com/giampaolo/psutil/compare/release-0.7.0...release-0.7.1#files_bucket +0.7.0 - 2013-04-12 + - PyPI: https://pypi.org/project/psutil/0.7.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#070 + - Diff: https://github.com/giampaolo/psutil/compare/release-0.6.1...release-0.7.0#files_bucket +0.6.1 - 2012-08-16 + - PyPI: https://pypi.org/project/psutil/0.6.1/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#061 + - Diff: https://github.com/giampaolo/psutil/compare/release-0.6.0...release-0.6.1#files_bucket +0.6.0 - 2012-08-13 + - PyPI: https://pypi.org/project/psutil/0.6.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#060 + - Diff: https://github.com/giampaolo/psutil/compare/release-0.5.1...release-0.6.0#files_bucket +0.5.1 - 2012-06-29 + - PyPI: https://pypi.org/project/psutil/0.5.1/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#051 + - Diff: https://github.com/giampaolo/psutil/compare/release-0.5.0...release-0.5.1#files_bucket +0.5.0 - 2012-06-27 + - PyPI: https://pypi.org/project/psutil/0.5.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#050 + - Diff: https://github.com/giampaolo/psutil/compare/release-0.4.1...release-0.5.0#files_bucket +0.4.1 - 2011-12-14 + - PyPI: https://pypi.org/project/psutil/0.4.1/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#041 + - Diff: https://github.com/giampaolo/psutil/compare/release-0.4.0...release-0.4.1#files_bucket +0.4.0 - 2011-10-29 + - PyPI: https://pypi.org/project/psutil/0.4.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#040 + - Diff: https://github.com/giampaolo/psutil/compare/release-0.3.0...release-0.4.0#files_bucket +0.3.0 - 2011-07-08 + - PyPI: https://pypi.org/project/psutil/0.3.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#030 + - Diff: https://github.com/giampaolo/psutil/compare/release-0.2.1...release-0.3.0#files_bucket +0.2.1 - 2011-03-20 + - PyPI: https://pypi.org/project/psutil/0.2.1/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#021 + - Diff: https://github.com/giampaolo/psutil/compare/release-0.2.0...release-0.2.1#files_bucket +0.2.0 - 2010-11-13 + - PyPI: https://pypi.org/project/psutil/0.2.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#020 + - Diff: https://github.com/giampaolo/psutil/compare/release-0.1.3...release-0.2.0#files_bucket +0.1.3 - 2010-03-02 + - PyPI: https://pypi.org/project/psutil/0.1.3/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#013 + - Diff: https://github.com/giampaolo/psutil/compare/release-0.1.2...release-0.1.3#files_bucket +0.1.2 - 2009-05-06 + - PyPI: https://pypi.org/project/psutil/0.1.2/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#012 + - Diff: https://github.com/giampaolo/psutil/compare/release-0.1.1...release-0.1.2#files_bucket +0.1.1 - 2009-03-06 + - PyPI: https://pypi.org/project/psutil/0.1.1/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#011 + - Diff: https://github.com/giampaolo/psutil/compare/release-0.1.0...release-0.1.1#files_bucket +0.1.0 - 2009-01-27 + - PyPI: https://pypi.org/project/psutil/0.1.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#010 + - Diff: https://github.com/giampaolo/psutil/compare/d84cc9a783d977368a64016cdb3568d2c9bceacc...release-0.1.0#files_bucket +``` + +---------------------------------------- + +TITLE: Process.cpu_affinity() Support on FreeBSD +DESCRIPTION: Adds support for Process.cpu_affinity() functionality on FreeBSD systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_404 + +LANGUAGE: python +CODE: +``` +# Enhancement: add support for Process.cpu_affinity() on FreeBSD. +# Implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: Enabling psutil Debug Mode on Windows +DESCRIPTION: Demonstrates how to enable debug mode for psutil on Windows by setting the PSUTIL_DEBUG environment variable. This can provide additional information for debugging issues. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_104 + +LANGUAGE: batch +CODE: +``` +set PSUTIL_DEBUG=1 python.exe script.py +psutil-debug [psutil/arch/windows/proc.c:90]> NtWow64ReadVirtualMemory64(pbi64.PebBaseAddress) -> 998 (Unknown error) (ignored) +``` + +---------------------------------------- + +TITLE: Process.oneshot() Context Manager +DESCRIPTION: Introduces the Process.oneshot() context manager for faster Process method calls, especially on Windows. It optimizes the retrieval of process information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_270 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +p = Process() +with p.oneshot(): + # Access multiple process attributes efficiently + pid = p.pid + name = p.name() + status = p.status() + # ... and so on +``` + +---------------------------------------- + +TITLE: Process I/O Niceness/Priority (Linux) +DESCRIPTION: Introduces per-process I/O niceness or priority settings on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_500 + +LANGUAGE: python +CODE: +``` +p.ionice() +``` + +---------------------------------------- + +TITLE: Process.ionice() Enhancement (Windows) +DESCRIPTION: Introduces the ability to set process high I/O priority on Windows. New constants for I/O priority levels are also exposed. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_162 + +LANGUAGE: python +CODE: +``` +Process.ionice() +IOPRIO_VERYLOW +IOPRIO_LOW +IOPRIO_NORMAL +IOPRIO_HIGH +``` + +---------------------------------------- + +TITLE: Project Migration and Version Control Changes +DESCRIPTION: Notes the migration of the project from Google Code to GitHub and from Mercurial to Git version control. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_400 + +LANGUAGE: git +CODE: +``` +# Enhancement: project moved from Google Code to Github; code moved from Mercurial to Git. +# Implemented in psutil version 2.1.2 +``` + +---------------------------------------- + +TITLE: users() Alias Handling on Linux +DESCRIPTION: Ensures that users() on Linux correctly handles ":0" as an alias for "localhost". + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_375 + +LANGUAGE: python +CODE: +``` +# Original issue: users() correctly handles ":0" as an alias for "localhost" on Linux. +# Fix implemented in psutil version 2.1.0 +``` + +---------------------------------------- + +TITLE: Process Threads Information +DESCRIPTION: Returns a list of named tuples, each representing a thread within the process. Includes thread ID, user time, and system time. Requires root privileges on OpenBSD. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_59 + +LANGUAGE: python +CODE: +``` +import psutil + +p = psutil.Process() + +# Get information about threads +for thread in p.threads(): + print(thread) +``` + +---------------------------------------- + +TITLE: Process.children() and Process.name() Performance Improvements +DESCRIPTION: Significant performance improvements have been made to `Process.children()` (on Windows, an order of magnitude faster) and `Process.name()` (on Windows, an order of magnitude faster; on POSIX, slightly faster due to avoiding redundant `cmdline()` retrieval). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_442 + +LANGUAGE: python +CODE: +``` +import psutil + +p = psutil.Process() + +# These calls are now faster: +children = p.children() +process_name = p.name() +``` + +---------------------------------------- + +TITLE: Process Wait and Popen +DESCRIPTION: Demonstrates waiting for a process to terminate and using the psutil.Popen class for enhanced subprocess management. Covers different return values on UNIX and Windows, timeout handling, and accessing process attributes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_79 + +LANGUAGE: python +CODE: +``` +import psutil + +# Wait for a process PID to terminate +p = psutil.Process(9891) +p.terminate() +exit_code = p.wait() +print(f"Process exited with: {exit_code}") + +# Using psutil.Popen +from subprocess import PIPE +p_popen = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"], stdout=PIPE) +print(f"Process name: {p_popen.name()}") +print(f"Process username: {p_popen.username()}") +stdout, stderr = p_popen.communicate() +print(f"Output: {stdout.decode()}") +result = p_popen.wait(timeout=2) +print(f"Wait result: {result}") +``` + +---------------------------------------- + +TITLE: FreeBSD Sensor Temperatures Support +DESCRIPTION: Adds support for retrieving sensor temperature data on FreeBSD systems using the sensors_temperatures() function. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_174 + +LANGUAGE: python +CODE: +``` +# [FreeBSD]: added support for sensors_temperatures(). +``` + +---------------------------------------- + +TITLE: CPU Times +DESCRIPTION: Retrieves system-wide CPU times (user, system, idle, etc.). Dependencies: None. Returns a named tuple with CPU time categories. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_2 + +LANGUAGE: python +CODE: +``` +>>> import psutil +>>> +>>> psutil.cpu_times() +scputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540, iowait=629.59, irq=0.0, softirq=19.42, steal=0.0, guest=0, guest_nice=0.0) +``` + +---------------------------------------- + +TITLE: WindowsService.description() Error Handling +DESCRIPTION: Fixes a potential failure in WindowsService.description() that could occur with ERROR_MUI_FILE_NOT_FOUND. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_263 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Windows]: WindowsService.description() method may fail with ERROR_MUI_FILE_NOT_FOUND. +# This ensures the service description can be retrieved even if MUI files are missing. +``` + +---------------------------------------- + +TITLE: Process.connections() 'kind' Argument +DESCRIPTION: The Process.connections() method now accepts a 'kind' argument to filter connections by different criteria (e.g., 'inet', 'all'). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_478 + +LANGUAGE: python +CODE: +``` +process.connections(kind='inet') +process.connections(kind='all') +``` + +---------------------------------------- + +TITLE: Process State and Control +DESCRIPTION: Provides a dictionary representation of the process's attributes. Checks if the process is still running. Allows suspending, resuming, terminating, and killing the process. `wait` blocks until the process terminates. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_33 + +LANGUAGE: python +CODE: +``` +p.as_dict() +# Expected output: {'status': 'running', 'num_ctx_switches': pctxsw(voluntary=63, involuntary=1), 'pid': 5457, ...} + +p.is_running() +# Expected output: True + +p.suspend() + +p.resume() + +p.terminate() + +p.kill() + +p.wait(timeout=3) +# Expected output: +``` + +---------------------------------------- + +TITLE: Process Executable Path Determination +DESCRIPTION: Improves the determination of the process executable path on FreeBSD by querying the kernel. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_495 + +LANGUAGE: python +CODE: +``` +p.exe() +``` + +---------------------------------------- + +TITLE: Process Methods and Properties +DESCRIPTION: This section details various methods and properties available for Process objects in psutil. It covers functionalities like accessing open files, network connections, sending signals, terminating processes, and retrieving process-specific information such as parent PID, UIDs, GIDs, name, executable path, command line, and creation time. It also notes changes in caching behavior and exception handling for disappearing processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_542 + +LANGUAGE: python +CODE: +``` +Process.open_files() +Process.connections() +Process.send_signal(signal) +Process.terminate() +Process.ppid() +Process.uids() +Process.gids() +Process.name() +Process.exe() +Process.cmdline() +Process.create_time() +``` + +---------------------------------------- + +TITLE: psutil Version History +DESCRIPTION: This section lists the release history of the psutil library. Each entry includes the version number, release date, and links to the PyPI page for that version, the 'what's new' changelog, and a diff of the changes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_107 + +LANGUAGE: python +CODE: +``` +5.6.2 - 2019-03-11: + - Link to PyPI: https://pypi.org/project/psutil/5.6.2/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#562 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.6.1...release-5.6.2#files_bucket + +5.6.1 - 2019-03-05: + - Link to PyPI: https://pypi.org/project/psutil/5.6.1/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#561 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.6.0...release-5.6.1#files_bucket + +5.6.0 - 2019-02-15: + - Link to PyPI: https://pypi.org/project/psutil/5.6.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#560 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.5.1...release-5.6.0#files_bucket + +5.5.1 - 2019-01-23: + - Link to PyPI: https://pypi.org/project/psutil/5.5.1/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#551 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.5.0...release-5.5.1#files_bucket + +5.5.0 - 2018-10-30: + - Link to PyPI: https://pypi.org/project/psutil/5.5.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#550 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.4.8...release-5.5.0#files_bucket + +5.4.8 - 2018-08-14: + - Link to PyPI: https://pypi.org/project/psutil/5.4.8/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#548 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.4.7...release-5.4.8#files_bucket + +5.4.7 - 2018-06-07: + - Link to PyPI: https://pypi.org/project/psutil/5.4.7/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#547 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.4.6...release-5.4.7#files_bucket + +5.4.6 - 2018-04-13: + - Link to PyPI: https://pypi.org/project/psutil/5.4.6/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#546 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.4.5...release-5.4.6#files_bucket + +5.4.5 - 2018-04-13: + - Link to PyPI: https://pypi.org/project/psutil/5.4.5/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#545 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.4.4...release-5.4.5#files_bucket + +5.4.4 - 2018-01-01: + - Link to PyPI: https://pypi.org/project/psutil/5.4.4/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#544 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.4.3...release-5.4.4#files_bucket + +5.4.3 - 2017-12-07: + - Link to PyPI: https://pypi.org/project/psutil/5.4.3/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#543 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.4.2...release-5.4.3#files_bucket + +5.4.2 - 2017-11-08: + - Link to PyPI: https://pypi.org/project/psutil/5.4.2/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#542 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.4.1...release-5.4.2#files_bucket + +5.4.1 - 2017-10-12: + - Link to PyPI: https://pypi.org/project/psutil/5.4.1/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#541 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.4.0...release-5.4.1#files_bucket + +5.4.0 - 2017-09-10: + - Link to PyPI: https://pypi.org/project/psutil/5.4.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#540 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.3.1...release-5.4.0#files_bucket + +5.3.1 - 2017-09-01: + - Link to PyPI: https://pypi.org/project/psutil/5.3.1/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#531 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.3.0...release-5.3.1#files_bucket + +5.3.0 - 2017-04-10: + - Link to PyPI: https://pypi.org/project/psutil/5.3.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#530 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.2.2...release-5.3.0#files_bucket + +5.2.2 - 2017-03-24: + - Link to PyPI: https://pypi.org/project/psutil/5.2.2/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#522 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.2.1...release-5.2.2#files_bucket + +5.2.1 - 2017-03-05: + - Link to PyPI: https://pypi.org/project/psutil/5.2.1/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#521 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.2.0...release-5.2.1#files_bucket + +5.2.0 - 2017-02-07: + - Link to PyPI: https://pypi.org/project/psutil/5.2.0/#files + - What's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#520 + - Diff: https://github.com/giampaolo/psutil/compare/release-5.1.3...release-5.2.0#files_bucket +``` + +---------------------------------------- + +TITLE: Process Network Connections (macOS Rewrite) +DESCRIPTION: Rewrites the `Process.connections()` implementation in C for macOS, removing the dependency on `lsof` and improving performance. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_503 + +LANGUAGE: python +CODE: +``` +p.connections() +``` + +---------------------------------------- + +TITLE: psutil API Documentation +DESCRIPTION: Provides documentation for various psutil functions related to process and system information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_269 + +LANGUAGE: APIDOC +CODE: +``` +Process: + OpenProcess(pid: int) -> Process + Opens a process by its PID. + Parameters: + pid: The process ID. + Returns: + A Process object representing the opened process. + Notes: + On Windows, checks if the PID is actually running. + + wait(timeout: Optional[float] = None) -> None + Wait for the process to terminate. + Parameters: + timeout: Optional timeout in seconds. If None, waits indefinitely. + Notes: + On Windows, may erroneously return sooner if PID is still alive. + + terminate() -> None + Terminate the process. + Raises: + AccessDenied: If the user lacks permissions. + Notes: + On Windows, may raise AccessDenied even if the process already died. + + cpu_times() -> namedtuple + Return a named tuple with user and system CPU time. + On Windows, fields #3 and #4 were int instead of float. + + connections(kind: str = 'inet') -> List[namedtuple] + Return a list of network connections opened by the process. + Parameters: + kind: Type of connections to return ('inet', 'inet4', 'inet6', 'unix'). + Returns: + A list of connection objects. + Notes: + On Linux/FreeBSD/OpenBSD, 'raddr' is now "" instead of None for UNIX sockets. + + io_counters(pernic: bool = False) -> namedtuple + Return a tuple of system-wide I/O statistics. + Parameters: + pernic: If True, return per network interface statistics. + Returns: + A tuple containing I/O statistics. + Notes: + On Windows, has 'other_count' and 'other_bytes' fields. + On Linux, has 'read_chars' and 'write_chars' fields. + + cpu_affinity(cpus: Optional[List[int]] = None) -> List[int] + Get or set the CPU affinity of a process. + Parameters: + cpus: A list of CPU IDs to set affinity to. If None, returns current affinity. + An empty list [] sets affinity to all eligible CPUs. + Returns: + A list of CPU IDs the process is allowed to run on. + + cpu_num() -> int + Return the CPU number the process is currently running on. + + cwd() -> str + Return the current working directory of a process. + Raises: + NoSuchProcess: If the process does not exist. + ZombieProcess: If the process is a zombie. + + username() -> str + Return the username of the process owner. + + open_files() -> List[namedtuple] + Return a list of files opened by the process. + +sensors_temperatures() -> Dict[str, List[namedtuple]] + Return a dictionary of system temperatures. + Supported on Linux. + May raise ENODEV or OSError on Linux. + +sensors_fans() -> Dict[str, List[namedtuple]] + Return a dictionary of system fan speeds. + Supported on Linux. + +sensors_battery() -> namedtuple + Return a tuple with battery status information. + Supported on Linux and Windows. + Fields include 'percent', 'secsleft', 'power_plugged', 'time_remaining', 'charge_level', 'status', 'name', 'label'. + 'percent' is a float for better precision. + 'power_plugged' may be None on Linux. + 'name' and 'label' are strings (not bytes) on Python 3 for Linux. + +cpu_freq(percpu: bool = False) -> Union[float, List[float]] + Return CPU frequency as a number or a list of numbers. + Parameters: + percpu: If True, return frequency for each CPU core. + Returns: + A float or a list of floats representing CPU frequencies. + May return None on some Linux versions. + +virtual_memory() -> namedtuple + Return a tuple with memory utilization statistics. + May raise ValueError on Ubuntu 14.04. + May fail on FreeBSD 12 due to missing sysctl parameter. + +disk_io_counters(perdisk: bool = False) -> Dict[str, namedtuple] + Return system-wide disk I/O statistics. + Parameters: + perdisk: If True, return statistics for each disk. + Returns: + A dictionary of disk I/O statistics. + May raise TypeError on Linux with Python 3. + May miscalculate sector size on Linux. + +pid_exists(pid: int) -> bool + Check if a process with the given PID exists. + On Linux, does not return True for thread IDs. + +users() -> List[namedtuple] + Return a list of currently logged in users. + +psutil.Popen(cmd, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=0, encoding=None, errors=None, env_copy=True, text=None, pipesize=-1) + A Popen subclass that integrates with psutil. + wait() behavior corrected for processes killed by signals. +``` + +---------------------------------------- + +TITLE: Process Parent and Ancestor Information +DESCRIPTION: Methods to retrieve parent and ancestor processes. `parent()` returns the parent process as a `Process` object, handling PID reuse. `parents()` returns a list of all parent `Process` instances. Returns `None` or an empty list if no parents are known. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_45 + +LANGUAGE: APIDOC +CODE: +``` +.. method:: parent() + + Utility method which returns the parent process as a :class:`Process` + object, preemptively checking whether PID has been reused. If no parent + PID is known return ``None``. + See also :meth:`ppid` and :meth:`parents` methods. + +.. method:: parents() + + Utility method which return the parents of this process as a list of + :class:`Process` instances. If no parents are known return an empty list. + See also :meth:`ppid` and :meth:`parent` methods. + + .. versionadded:: 5.6.0 +``` + +---------------------------------------- + +TITLE: Process.num_fds() and Process.open_files() Handling for PID 0 +DESCRIPTION: On OpenBSD, Process.num_fds() and Process.open_files() might fail with NoSuchProcess for PID 0. This change ensures they now return null values (0 and [] respectively) in such cases. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_33 + +LANGUAGE: python +CODE: +``` +try: + fds = proc.num_fds() + open_files = proc.open_files() +except psutil.NoSuchProcess: + fds = 0 + open_files = [] +``` + +---------------------------------------- + +TITLE: net_connections(), Process.connections() Windows Performance +DESCRIPTION: net_connections() and Process.connections() are now 10% faster on Windows. This performance improvement enhances network connection monitoring. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_99 + +LANGUAGE: APIDOC +CODE: +``` +net_connections(), Process.connections() + - Are 10% faster on Windows. +``` + +---------------------------------------- + +TITLE: Battery Status +DESCRIPTION: Returns battery status information, including percentage remaining, estimated time left in seconds, and whether the power adapter is plugged in. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/README.rst#_snippet_20 + +LANGUAGE: python +CODE: +``` +psutil.sensors_battery() +# Output: sbattery(percent=93, secsleft=16628, power_plugged=False) +``` + +---------------------------------------- + +TITLE: UNC Path Handling in Windows +DESCRIPTION: Bug fix for psutil version 7.0.1: Improved handling of UNC paths for Windows APIs like Process.memory_maps(), Process.exe(), and Process.open_files(). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_4 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +# Example of handling UNC paths (conceptual) +# process = Process() +# try: +# maps = process.memory_maps(filepath='\\?\C:\Windows\Temp') +# except Exception as e: +# print(f"Error: {e}") +``` + +---------------------------------------- + +TITLE: Process Information as Dictionary +DESCRIPTION: Utility method to retrieve multiple process attributes as a dictionary. Allows specifying which attributes to retrieve or retrieves all public read-only attributes by default. Handles potential errors by assigning a default value. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_42 + +LANGUAGE: python +CODE: +``` +import psutil + +p = psutil.Process() + +# Get all attributes as a dictionary +all_attrs_dict = p.as_dict() +print("All attributes:", all_attrs_dict) + +# Get specific attributes +specific_attrs = ['pid', 'name', 'cpu_percent', 'memory_info'] +specific_attrs_dict = p.as_dict(attrs=specific_attrs) +print("Specific attributes:", specific_attrs_dict) + +# Get attributes with a default value for missing ones +attrs_with_default = p.as_dict(attrs=['pid', 'non_existent_attr'], ad_value='N/A') +print("Attributes with default value:", attrs_with_default) +``` + +---------------------------------------- + +TITLE: Process Open Files (macOS Rewrite) +DESCRIPTION: Rewrites the `Process.open_files()` implementation in C for macOS, removing the dependency on `lsof` and improving performance. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_502 + +LANGUAGE: python +CODE: +``` +p.open_files() +``` + +---------------------------------------- + +TITLE: Process Command Line (macOS Fix) +DESCRIPTION: Fixes an issue where `Process.cmdline()` was empty on macOS 64-bit systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_504 + +LANGUAGE: python +CODE: +``` +p.cmdline() +``` + +---------------------------------------- + +TITLE: Exposing OS Constants +DESCRIPTION: OS-specific constants such as psutil.LINUX, psutil.OSX, etc., are now exposed, allowing for easier platform detection within scripts. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_328 + +LANGUAGE: python +CODE: +``` +if psutil.LINUX: + print('Running on Linux') +``` + +---------------------------------------- + +TITLE: System Per-CPU Utilization and Times +DESCRIPTION: Adds functionality to retrieve system per-CPU percentage utilization and times using Process.cpu_times() and Process.cpu_percent(). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_485 + +LANGUAGE: python +CODE: +``` +import psutil + +# Get CPU times for the system +system_cpu_times = psutil.cpu_times(percpu=True) + +# Get CPU percentage for the system +system_cpu_percent = psutil.cpu_percent(interval=1, percpu=True) +``` + +---------------------------------------- + +TITLE: Process.cmdline() error handling on NetBSD +DESCRIPTION: Fixes an issue on NetBSD where Process.cmdline() could raise a MemoryError if the command line contained non-encodable characters. This improves robustness when retrieving command lines with unusual character sets. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_104 + +LANGUAGE: python +CODE: +``` +p.cmdline() +# Now handles non-encodable characters gracefully. +``` + +---------------------------------------- + +TITLE: psutil API Documentation +DESCRIPTION: Provides documentation for various psutil functions and methods, including process information, system utilization, and platform-specific features. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_170 + +LANGUAGE: APIDOC +CODE: +``` +psutil Module Documentation: + +General Functions: + cpu_freq() -> tuple or None + Returns a tuple of (min, max) CPU frequency in MHz, or None if undetermined. + On Linux, may return 0.0 if min/max cannot be determined. + + cpu_count(logical: bool = True) -> int + Returns the number of CPUs. logical=True returns logical cores, logical=False returns physical cores. + On Windows, logical=False could cause a crash in older versions. + + disk_partitions(all: bool = False) -> list + Returns a list of disk partitions. all=True includes all partitions. + On Linux, handles corner cases where /etc/mtab might not exist. + + pids() -> list + Returns a list of all running process IDs, sorted in ascending order. + + process_iter() -> iterator + Returns an iterator yielding Process instances for all running processes. + Thread-safe since version 5.6.0. + +Process Object Methods: + Process.name() -> str + Returns the process name. + On SunOS, may raise SystemError. + On Windows, uses QueryFullProcessImageNameW for accuracy. + + Process.exe() -> str + Returns the executable path of the process. + On Windows, uses QueryFullProcessImageNameW for accuracy. + + Process.cmdline() -> list + Returns the command line arguments of the process. + On SunOS, may raise SystemError. + On OSX, may raise OSError on failed malloc(). + + Process.environ() -> dict + Returns the environment variables of the process. + On Windows, raises AccessDenied when querying 64-bit processes in 32-bit-WoW mode. + + Process.parents() -> list + Returns a list of parent Process instances. + + Process.ionice(priority: int) + Sets the I/O priority of the process on Windows. + Accepts IOPRIO_VERYLOW, IOPRIO_LOW, IOPRIO_NORMAL, IOPRIO_HIGH. + + Process.suspend() + Suspends the process on Windows using NtSuspendProcess. + + Process.resume() + Resumes the process on Windows using NtResumeProcess. + + Process.memory_info_ex() -> tuple + Returns extended memory information, including USS. + On Windows, USS calculation uses the system PAGESIZE for accuracy. + + Process.memory_full_info() -> tuple + Returns full memory information. On Windows, uses NtQueryVirtualMemory for USS. + +Context Managers: + Process.oneshot(): + Context manager for efficient retrieval of process information. + Ensures exceptions are correctly converted to psutil exceptions (e.g., NoSuchProcess, AccessDenied). + On NetBSD, may return incomplete results if using Process.connections() within oneshot(). + +Error Handling: + AccessDenied: Raised when access to a process is denied. + NoSuchProcess: Raised when a process with the specified PID does not exist. + SystemError: May be raised on SunOS for Process.name() and Process.cmdline(). + OSError: May be raised on OSX for Process.cmdline() on failed malloc(). + +Platform Specific Notes: + Windows: + - Process.ionice() available. + - Process.suspend() and Process.resume() optimized. + - Process.memory_full_info() uses NtQueryVirtualMemory. + - Process.name() and Process.exe() use QueryFullProcessImageNameW. + - Process.environ() raises AccessDenied for WoW64 processes. + - Process.memory_info_ex() USS calculation corrected. + - Crash on import due to missing rtlIpv6AddressToStringA on Wine fixed. + - Crash on Process.memory_full_info() fixed. + - Process.name() and Process.exe() failures fixed. + - AccessDenied handling for OSError.winerror improved. + - Error handling for private NTSTATUS Windows APIs improved. + - Crash in cpu_count(logical=False) fixed. + - SE DEBUG set for current process. + + Linux: + - cpu_freq() returns 0.0 when min/max cannot be determined. + - Tests made invariant to LANG setting. + - cpu_freq() handles empty /sys/devices/system/cpu/cpufreq/. + - disk_partitions() handles missing /etc/mtab. + - cpu_freq() returns all CPUs on Raspberry-pi 3. + + AIX, SunOS: + - AttributeError when using Process methods with Process.oneshot() fixed. + - On SunOS, Process.name() and Process.cmdline() may raise SystemError. + - On SunOS, net_if_addrs() uses free() against ifap struct on error. + + OSX: + - Process.cmdline() and Process.environ() may raise OSError on failed malloc(). + + NetBSD: + - Process.connections() may return incomplete results with Process.oneshot(). + +Incompatible API Changes: + - Process.memory_maps() removed (version 5.6.0). +``` + +---------------------------------------- + +TITLE: psutil.Process.memory_full_info() +DESCRIPTION: Explains the `memory_full_info()` method, which provides additional memory metrics like USS and PSS, offering a more accurate view of process memory consumption. Notes that it may require higher privileges and is slower than `memory_info()`. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_70 + +LANGUAGE: APIDOC +CODE: +``` +method:: memory_full_info() + + Returns the same information as :meth:`memory_info`, plus, on some platforms (Linux, macOS, Windows), also provides additional metrics (USS, PSS and swap). + + The additional metrics provide a better representation of "effective" process memory consumption (in case of USS) as explained in detail in this `blog post `__. + It does so by passing through the whole process address. As such it usually requires higher user privileges than :meth:`memory_info` and is considerably slower. + On platforms where extra fields are not implemented this simply returns the same metrics as :meth:`memory_info`. + + - **uss**: Unique Set Size. Memory unique to a process that would be freed if the process terminated. + - **pss**: Proportional Set Size. Memory shared with other processes, accounted proportionally. + +.. versionchanged:: 4.0.0 + Multiple fields are returned, not only `rss` and `vms`. +``` + +---------------------------------------- + +TITLE: Process.connections() UNIX Socket Handling (Linux/FreeBSD/OpenBSD) +DESCRIPTION: Standardizes the handling of UNIX sockets in Process.connections() across Linux, FreeBSD, and OpenBSD. The 'raddr' field now returns an empty string ('') instead of None for UNIX sockets. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_224 + +LANGUAGE: python +CODE: +``` +# Original issue: Linux / FreeBSD / OpenBSD: Process.connections() 'raddr' is now set to "" instead of None when retrieving UNIX sockets. +# This change ensures consistent data types for remote addresses of UNIX sockets. +``` + +---------------------------------------- + +TITLE: Process.cmdline() retrieval on AIX +DESCRIPTION: Fixes an issue on AIX where Process.cmdline() could not retrieve the complete command line for a process. This ensures that the full command line arguments are accessible. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_108 + +LANGUAGE: python +CODE: +``` +p.cmdline() +# Now returns the complete command line string. +``` + +---------------------------------------- + +TITLE: psutil Version History +DESCRIPTION: This section lists the release history of the psutil library. It includes version numbers, release dates, and links to PyPI for downloads, changelogs, and code differences between versions. This information is useful for tracking the evolution of the library and understanding changes between releases. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_109 + +LANGUAGE: text +CODE: +``` +3.2.0 - 2015-07-15 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#320 + diff: https://github.com/giampaolo/psutil/compare/release-3.1.1...release-3.2.0#files_bucket +3.1.1 - 2015-07-15 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#311 + diff: https://github.com/giampaolo/psutil/compare/release-3.1.0...release-3.1.1#files_bucket +3.1.0 - 2015-06-18 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#310 + diff: https://github.com/giampaolo/psutil/compare/release-3.0.1...release-3.1.0#files_bucket +3.0.1 - 2015-06-13 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#301 + diff: https://github.com/giampaolo/psutil/compare/release-3.0.0...release-3.0.1#files_bucket +3.0.0 - 2015-02-02 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#300 + diff: https://github.com/giampaolo/psutil/compare/release-2.2.1...release-3.0.0#files_bucket +2.2.1 - 2015-01-06 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#221 + diff: https://github.com/giampaolo/psutil/compare/release-2.2.0...release-2.2.1#files_bucket +2.2.0 - 2014-09-26 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#220 + diff: https://github.com/giampaolo/psutil/compare/release-2.1.3...release-2.2.0#files_bucket +2.1.3 - 2014-09-21 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#213 + diff: https://github.com/giampaolo/psutil/compare/release-2.1.2...release-2.1.3#files_bucket +2.1.2 - 2014-04-30 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#212 + diff: https://github.com/giampaolo/psutil/compare/release-2.1.1...release-2.1.2#files_bucket +2.1.1 - 2014-04-08 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#211 + diff: https://github.com/giampaolo/psutil/compare/release-2.1.0...release-2.1.1#files_bucket +2.1.0 - 2014-03-10 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#210 + diff: https://github.com/giampaolo/psutil/compare/release-2.0.0...release-2.1.0#files_bucket +2.0.0 - 2013-11-25 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#200 + diff: https://github.com/giampaolo/psutil/compare/release-1.2.1...release-2.0.0#files_bucket +1.2.1 - 2013-11-20 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#121 + diff: https://github.com/giampaolo/psutil/compare/release-1.2.0...release-1.2.1#files_bucket +1.2.0 - 2013-10-22 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#120 + diff: https://github.com/giampaolo/psutil/compare/release-1.1.2...release-1.2.0#files_bucket +1.1.2 - 2013-10-08 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#112 + diff: https://github.com/giampaolo/psutil/compare/release-1.1.1...release-1.1.2#files_bucket +1.1.1 - 2013-09-28 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#111 + diff: https://github.com/giampaolo/psutil/compare/release-1.1.0...release-1.1.1#files_bucket +1.1.0 - 2013-07-12 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#110 + diff: https://github.com/giampaolo/psutil/compare/release-1.0.1...release-1.1.0#files_bucket +1.0.1 - 2013-07-10 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#101 + diff: https://github.com/giampaolo/psutil/compare/release-1.0.0...release-1.0.1#files_bucket +1.0.0 - 2013-05-03 + what's new: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#100 + diff: https://github.com/giampaolo/psutil/compare/release-0.7.1...release-1.0.0#files_bucket +``` + +---------------------------------------- + +TITLE: psutil CREDITS Link +DESCRIPTION: Provides a link to the CREDITS file, which contributors should update when making changes to the project. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/CONTRIBUTING.md#_snippet_3 + +LANGUAGE: markdown +CODE: +``` +[CREDITS](https://github.com/giampaolo/psutil/blob/master/CREDITS) +``` + +---------------------------------------- + +TITLE: psutil Process API Documentation +DESCRIPTION: Comprehensive API documentation for psutil Process methods. This includes details on checking if a process is running, sending signals, suspending, resuming, terminating, killing processes, and waiting for process completion. It also covers deprecated methods and version changes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_78 + +LANGUAGE: APIDOC +CODE: +``` +.. method:: connections() + + Same as :meth:`net_connections` (deprecated). + + .. warning:: + deprecated in version 6.0.0; use :meth:`net_connections` instead. + +.. method:: is_running() + + Return whether the current process is running in the current process list. + This is reliable also in case the process is gone and its PID reused by + another process, therefore it must be preferred over doing + ``psutil.pid_exists(p.pid)``. + If PID has been reused this method will also remove the process from + :func:`process_iter()` internal cache. + + .. note:: + this will return ``True`` also if the process is a zombie + (``p.status() == psutil.STATUS_ZOMBIE``). + + .. versionchanged:: 6.0.0 : automatically remove process from + :func:`process_iter()` internal cache if PID has been reused by another + process. + +.. method:: send_signal(signal) + + Send a signal to process (see `signal module`_ constants) preemptively + checking whether PID has been reused. + On UNIX this is the same as ``os.kill(pid, sig)``. + On Windows only *SIGTERM*, *CTRL_C_EVENT* and *CTRL_BREAK_EVENT* signals + are supported and *SIGTERM* is treated as an alias for :meth:`kill()`. + See also how to `kill a process tree <#kill-process-tree>`__ and + `terminate my children <#terminate-my-children>`__. + + .. versionchanged:: + 3.2.0 support for CTRL_C_EVENT and CTRL_BREAK_EVENT signals on Windows + was added. + +.. method:: suspend() + + Suspend process execution with *SIGSTOP* signal preemptively checking + whether PID has been reused. + On UNIX this is the same as ``os.kill(pid, signal.SIGSTOP)``. + On Windows this is done by suspending all process threads execution. + +.. method:: resume() + + Resume process execution with *SIGCONT* signal preemptively checking + whether PID has been reused. + On UNIX this is the same as ``os.kill(pid, signal.SIGCONT)``. + On Windows this is done by resuming all process threads execution. + +.. method:: terminate() + + Terminate the process with *SIGTERM* signal preemptively checking + whether PID has been reused. + On UNIX this is the same as ``os.kill(pid, signal.SIGTERM)``. + On Windows this is an alias for :meth:`kill`. + See also how to `kill a process tree <#kill-process-tree>`__ and + `terminate my children <#terminate-my-children>`__. + +.. method:: kill() + + Kill the current process by using *SIGKILL* signal preemptively + checking whether PID has been reused. + On UNIX this is the same as ``os.kill(pid, signal.SIGKILL)``. + On Windows this is done by using `TerminateProcess`_. + See also how to `kill a process tree <#kill-process-tree>`__ and + `terminate my children <#terminate-my-children>`__. + +.. method:: wait(timeout=None) + +``` + +---------------------------------------- + +TITLE: CPU Utilization Percentage +DESCRIPTION: Details on the `cpu_percent()` method for both individual processes and the system. It highlights changes in behavior regarding immediate return values and references an issue tracker for more information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_543 + +LANGUAGE: python +CODE: +``` +Process.cpu_percent(interval=None) +cpu_percent(interval=None, percpu=False) +``` + +---------------------------------------- + +TITLE: Process.exe() on FreeBSD +DESCRIPTION: Resolves an issue on FreeBSD where Process.exe() could fail with an OSError (ENOENT). This ensures the executable path can be retrieved reliably. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_274 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +try: + p = Process() + exe_path = p.exe() + print(f"Executable path: {exe_path}") +except OSError as e: + print(f"Error getting executable path: {e}") +``` + +---------------------------------------- + +TITLE: Process.exe() Exception Handling on Linux +DESCRIPTION: Addresses rare conditions on Linux where Process.exe(), Process.open_files(), and Process.connections() could raise OSError(ESRCH) instead of NoSuchProcess. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_378 + +LANGUAGE: python +CODE: +``` +# Original issue: in rare conditions Process.exe(), Process.open_files() and Process.connections() can raise OSError(ESRCH) instead of NoSuchProcess_. +# Fix implemented in psutil version 2.1.2 +``` + +---------------------------------------- + +TITLE: Process.cwd() Support on FreeBSD +DESCRIPTION: Adds support for Process.cwd() on FreeBSD systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_475 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +p = Process() +cwd = p.cwd() +``` + +---------------------------------------- + +TITLE: Process str() and repr() Enhancements +DESCRIPTION: The Process class now provides more information about the process in str() and repr() outputs, including status and exit code. This enhances the debugging and monitoring capabilities. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_96 + +LANGUAGE: APIDOC +CODE: +``` +Process class + - Provides more info about the process on str() and repr() (status and exit code). +``` + +---------------------------------------- + +TITLE: Windows ARM64 Wheels Publishing +DESCRIPTION: Enhancement for psutil version 7.0.1: Publishing ARM64 wheels for Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_0 + +LANGUAGE: python +CODE: +``` +# No specific code snippet available for this enhancement, it refers to build/packaging changes. +``` + +---------------------------------------- + +TITLE: psutil Utility Scripts +DESCRIPTION: This section lists various utility scripts provided by the psutil library, each designed for a specific system monitoring or process management task. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_563 + +LANGUAGE: python +CODE: +``` +# cpu_distribution.py: Displays CPU utilization distribution. +# disk_usage.py: Shows disk usage statistics. +# free.py: Displays system memory usage. +# iotop.py: Monitors I/O usage by process. +# meminfo.py: Provides detailed memory information. +# netstat.py: Displays network connections and statistics. +# nettop.py: Monitors network traffic by process. +# pidof.py: Finds process IDs by name. +# pmap.py: Displays process memory map. +# procinfo.py: Shows detailed information about a process. +# procsmem.py: Displays process memory usage. +# ps.py: A simplified 'ps' command implementation. +# pstree.py: Displays processes in a tree format. +# top.py: A simplified 'top' command implementation. +``` + +---------------------------------------- + +TITLE: macOS Process.connections() EOPNOTSUPP Handling +DESCRIPTION: Addresses an issue on macOS where Process.connections() could crash with EOPNOTSUPP for a specific connection. This error is now ignored, improving stability. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_72 + +LANGUAGE: python +CODE: +``` +# Example of retrieving network connections for a process on macOS +# import psutil +# try: +# p = psutil.Process(pid) +# connections = p.connections() +# print(f"Number of connections: {len(connections)}") +# except psutil.NoSuchProcess: +# print("Process not found.") +# except Exception as e: +# print(f"Error retrieving connections: {e}") # EOPNOTSUPP is now handled internally. +``` + +---------------------------------------- + +TITLE: Process Suspend and Resume +DESCRIPTION: Describes the `Process.suspend()` and `Process.resume()` methods, which allow for controlling the execution state of a process. These functionalities are available on FreeBSD systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_545 + +LANGUAGE: python +CODE: +``` +Process.suspend() +Process.resume() +``` + +---------------------------------------- + +TITLE: virtual_memory() sysctl Parameter Handling (FreeBSD) +DESCRIPTION: Fixes virtual_memory() failures on FreeBSD 12 due to a missing sysctl parameter. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_236 + +LANGUAGE: python +CODE: +``` +# Original issue: [FreeBSD]: virtual_memory() may fail due to missing sysctl parameter on FreeBSD 12. +# This change ensures virtual_memory() works correctly on FreeBSD 12. +``` + +---------------------------------------- + +TITLE: Process Information Methods +DESCRIPTION: Provides access to various attributes and statistics of a process. These methods allow you to retrieve information such as the process name, command line, CPU times, memory usage, and more. Some methods may require specific privileges or might raise exceptions like AccessDenied or NoSuchProcess. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_558 + +LANGUAGE: APIDOC +CODE: +``` +Process.as_dict(attrs=None, ad_value=None) + Returns a dictionary with process information. + attrs: A list of attributes to retrieve. If None, all available attributes are returned. + ad_value: Value to use for attributes that raise AccessDenied. + +Process.children(recursive=False) + Returns a list of direct children of this process. + recursive: If True, return all descendants. + +Process.cmdline() + Returns the command line arguments of the process as a list of strings. + +Process.connections() + Returns a list of network connections opened by this process. + +Process.cpu_affinity() + Returns a list of CPUs this process is allowed to run on. + +Process.cpu_num() + Returns the CPU number the process is currently running on. + +Process.cpu_percent(interval=None) + Returns the process CPU utilization as a float. + interval: If None, returns the utilization since last call. If a float, calculates utilization over the specified interval. + +Process.cpu_times() + Returns a tuple of (user, system) CPU times. + +Process.create_time() + Returns the process creation time as a float timestamp. + +Process.cwd() + Returns the current working directory of the process as a string. + +Process.environ() + Returns the process environment variables as a dictionary. + +Process.exe() + Returns the executable path of the process as a string. + +Process.gids() + Returns the real, effective, and saved group IDs of the process. + +Process.io_counters(percpu=False) + Returns I/O statistics for the process. + percpu: If True, returns I/O statistics per CPU. + +Process.ionice(ioclass=None, value=None) + Gets or sets the I/O scheduling class and priority. + +Process.is_running() + Returns True if the process is running, False otherwise. + +Process.kill() + Kills the process. + +Process.memory_full_info() + Returns extended memory information for the process. + +Process.memory_info() + Returns memory usage statistics for the process. + +Process.memory_info_ex() + Returns extended memory usage statistics for the process. + +Process.memory_maps(grouped=True) + Returns a list of memory mappings for the process. + grouped: If True, group identical mappings. + +Process.memory_percent() + Returns the process memory utilization as a float. + +Process.name() + Returns the name of the process as a string. + +Process.net_connections(kind='inet') + Returns a list of network connections opened by this process. + kind: Type of connections to return ('inet', 'tcp', 'udp', 'all'). + +Process.nice() + Gets or sets the niceness of the process. + +Process.num_ctx_switches() + Returns the number of context switches performed by the process. + +Process.num_fds() + Returns the number of file descriptors opened by the process. + +Process.num_handles() + Returns the number of handles opened by the process (Windows specific). + +Process.num_threads() + Returns the number of threads in the process. + +Process.oneshot() + Context manager to optimize attribute retrieval. + +Process.open_files() + Returns a list of files opened by the process. + +Process.parent() + Returns the parent process object. + +``` + +---------------------------------------- + +TITLE: Memory Information Metrics +DESCRIPTION: Details the various memory metrics (rss, vms, shared, text, lib, data, dirty) and their meanings across Linux, macOS, BSD, Solaris, AIX, and Windows. Explains aliases and platform-specific interpretations. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_68 + +LANGUAGE: APIDOC +CODE: +``` +Memory Metrics Overview: + +All numbers are expressed in bytes. + +| Linux | macOS | BSD | Solaris | AIX | Windows | +|---------|---------|-------|---------|-----|------------------------------| +| rss | rss | rss | rss | rss | rss (alias for `wset`) | +| vms | vms | vms | vms | vms | vms (alias for `pagefile`) | +| shared | pfaults | text | | | num_page_faults | +| text | pageins | data | | | peak_wset | +| lib | | stack | | | wset | +| data | | | | | peak_paged_pool | +| dirty | | | | | paged_pool | +| | | | | | peak_nonpaged_pool | +| | | | | | nonpaged_pool | +| | | | | | pagefile | +| | | | | | peak_pagefile | +| | | | | | private | + +- **rss**: Resident Set Size. Non-swapped physical memory used by a process. + - UNIX: Matches "top"'s RES column. + - Windows: Alias for `wset`, matches "Mem Usage" of taskmgr.exe. + +- **vms**: Virtual Memory Size. Total virtual memory used by the process. + - UNIX: Matches "top"'s VIRT column. + - Windows: Alias for `pagefile`, matches "Mem Usage" "VM Size" of taskmgr.exe. + +- **shared**: (Linux) Memory potentially shared with other processes. Matches "top"'s SHR column. + +- **text**: (Linux, BSD) Text Resident Set (TRS). Memory devoted to executable code. Matches "top"'s CODE column. + +- **data**: (Linux, BSD) Data Resident Set (DRS). Physical memory devoted to non-executable code. Matches "top"'s DATA column. + +- **lib**: (Linux) Memory used by shared libraries. + +- **dirty**: (Linux) Number of dirty pages. + +- **pfaults**: (macOS) Number of page faults. + +- **pageins**: (macOS) Number of actual pageins. + +For Windows fields, refer to `PROCESS_MEMORY_COUNTERS_EX` documentation. +``` + +---------------------------------------- + +TITLE: Process.cwd() error on NetBSD +DESCRIPTION: Fixes an issue on NetBSD where Process.cwd() could return ENOENT instead of NoSuchProcess. This ensures consistent error reporting for non-existent current working directories. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_136 + +LANGUAGE: python +CODE: +``` +p.cwd() +# Now raises NoSuchProcess instead of ENOENT. +``` + +---------------------------------------- + +TITLE: New Script: pidof.py +DESCRIPTION: Introduction of a new utility script, pidof.py, for finding process IDs by name. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_406 + +LANGUAGE: python +CODE: +``` +# Enhancement: new pidof.py script. +# Implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: net_connections() MIB2_UDP_ENTRY Handling on Illumos +DESCRIPTION: Bug fix for psutil version 7.0.1: Corrected handling of MIB2_UDP_ENTRY in net_connections() on Illumos. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_11 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to internal implementation. +``` + +---------------------------------------- + +TITLE: OpenBSD cpu_freq() Support Added +DESCRIPTION: Introduces support for retrieving CPU frequency information on OpenBSD systems using the cpu_freq() function. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_59 + +LANGUAGE: python +CODE: +``` +# Example of retrieving CPU frequency on OpenBSD +# import psutil +# try: +# freq = psutil.cpu_freq() +# if freq: +# print(f"Current: {freq.current} MHz, Min: {freq.min} MHz, Max: {freq.max} MHz") +# except Exception as e: +# print(f"Error retrieving CPU frequency: {e}") +``` + +---------------------------------------- + +TITLE: FreeBSD CPU Frequency Support +DESCRIPTION: Introduces support for retrieving CPU frequency information on FreeBSD systems via the cpu_freq() function. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_175 + +LANGUAGE: python +CODE: +``` +# [FreeBSD]: added support for cpu_freq(). +``` + +---------------------------------------- + +TITLE: System Boot Time +DESCRIPTION: Adds a function to retrieve the system boot time. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_497 + +LANGUAGE: python +CODE: +``` +psutil.boot_time() +``` + +---------------------------------------- + +TITLE: Process Command Line +DESCRIPTION: Retrieves the command line arguments with which the process was called, as a list of strings. The return value is not cached because the command line of a process may change. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_39 + +LANGUAGE: APIDOC +CODE: +``` +cmdline() + Returns the command line this process has been called with as a list of strings. + The return value is not cached because the cmdline of a process may change. + Example: + >>> import psutil + >>> psutil.Process().cmdline() + ['python', 'manage.py', 'runserver'] + Returns: A list of strings representing the command line arguments. +``` + +---------------------------------------- + +TITLE: Process.connections(), Process.num_fds(), Process.threads() on OpenBSD +DESCRIPTION: Fixes an issue on OpenBSD where Process.connections(), Process.num_fds(), and Process.threads() returned an improper exception if the process had already terminated. This ensures correct error handling for gone processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_145 + +LANGUAGE: python +CODE: +``` +p.connections() +p.num_fds() +p.threads() +# Now correctly handle gone processes. +``` + +---------------------------------------- + +TITLE: getloadavg() calculation on Windows +DESCRIPTION: Introduces a new getloadavg() function that provides system load average calculations, including an emulated version for Windows. This allows cross-platform access to load average metrics. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_105 + +LANGUAGE: python +CODE: +``` +psutil.getloadavg() +# Returns a tuple of 1, 5, 15 minute load averages. +``` + +---------------------------------------- + +TITLE: Process.connections(), Process.num_fds(), Process.threads() on OpenBSD +DESCRIPTION: Fixes an issue on OpenBSD where Process.connections(), Process.num_fds(), and Process.threads() returned an improper exception if the process had already terminated. This ensures correct error handling for gone processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_116 + +LANGUAGE: python +CODE: +``` +p.connections() +p.num_fds() +p.threads() +# Now correctly handle gone processes. +``` + +---------------------------------------- + +TITLE: Process Instances Hashability +DESCRIPTION: Makes Process instances hashable, allowing them to be used in sets and other hash-based collections. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_399 + +LANGUAGE: python +CODE: +``` +# Enhancement: make Process instances hashable and usable with set() s. +# Implemented in psutil version 2.0.0 +``` + +---------------------------------------- + +TITLE: Process Caching and Utility Methods +DESCRIPTION: This snippet covers improvements to process attribute caching and the introduction of new utility methods. It highlights that certain `Process` properties are now cached after access and mentions the new `Process.as_dict()` method. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_457 + +LANGUAGE: python +CODE: +``` +Process.ppid(), Process.name(), Process.exe(), Process.cmdline(), Process.create_time() # Now cached after first access +Process.as_dict() # New method to return process information as a dictionary +``` + +---------------------------------------- + +TITLE: System Boot Time +DESCRIPTION: Returns the system boot time as seconds since the epoch. The value may be affected by system clock adjustments. On Windows, it might be off by 1 second across different processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_24 + +LANGUAGE: python +CODE: +``` +import psutil +import datetime + +boot_timestamp = psutil.boot_time() +boot_datetime = datetime.datetime.fromtimestamp(boot_timestamp) +print(f"System Boot Time: {boot_datetime.strftime('%Y-%m-%d %H:%M:%S')}") +``` + +---------------------------------------- + +TITLE: Linux disk_partitions() /dev/root Alias Handling +DESCRIPTION: Ensures that the '/dev/root' device alias used on some Linux distributions is correctly converted to the real root device path in disk_partitions(). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_68 + +LANGUAGE: python +CODE: +``` +# Example of retrieving disk partitions on Linux +# import psutil +# for partition in psutil.disk_partitions(): +# print(f"Device: {partition.device}, Mountpoint: {partition.mountpoint}") +# # The library now correctly resolves /dev/root if present. +``` + +---------------------------------------- + +TITLE: PEP 517/8 build backend +DESCRIPTION: Adds PEP 517/8 build backend and requirements specification for better pip integration. This modernizes the build process and improves compatibility with packaging standards. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_124 + +LANGUAGE: python +CODE: +``` +# Build system configuration update. +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes - psutil.Popen Constructor Exception +DESCRIPTION: Addresses an issue where the psutil.Popen constructor could raise an exception if the spawned process terminated very quickly after creation. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_435 + +LANGUAGE: python +CODE: +``` +# Fix for psutil.Popen constructor potentially raising exception on quick process termination +# Original issue: https://github.com/giampaolo/psutil/issues/193 +``` + +---------------------------------------- + +TITLE: Process.connections() IPv6 and Endianness Fixes +DESCRIPTION: Fixes issues with Process.connections() on platforms not supporting IPv6 and on big-endian architectures. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_481 + +LANGUAGE: python +CODE: +``` +# Fixes for Process.connections() related to IPv6 and endianness. +``` + +---------------------------------------- + +TITLE: Process.open_files() and Process.connections() OSError Handling (macOS) +DESCRIPTION: Improves OSError handling in Process.open_files() and Process.connections() on macOS when a process disappears, ensuring a proper exception is raised. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_303 + +LANGUAGE: python +CODE: +``` +from psutil import Process, NoSuchProcess + +try: + p = Process() + p.open_files() + p.connections() +except NoSuchProcess: + print("Process gone, handled correctly.") +except OSError as e: + print(f"OSError encountered: {e}") +``` + +---------------------------------------- + +TITLE: Process.open_files() Enhancements +DESCRIPTION: On Linux, Process.open_files() now returns three new fields: 'position', 'mode', and 'flags'. This provides more detailed information about open files associated with a process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_321 + +LANGUAGE: python +CODE: +``` +process.open_files() +``` + +---------------------------------------- + +TITLE: Process Open Files +DESCRIPTION: Adds per-process open files retrieval. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_513 + +LANGUAGE: python +CODE: +``` +p.open_files() +``` + +---------------------------------------- + +TITLE: Windows boot_time() Fix +DESCRIPTION: On Windows, the boot_time() function no longer wraps to 0 after 49 days, providing accurate boot time information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_333 + +LANGUAGE: python +CODE: +``` +psutil.boot_time() +``` + +---------------------------------------- + +TITLE: PEP 517/8 build backend +DESCRIPTION: Adds PEP 517/8 build backend and requirements specification for better pip integration. This modernizes the build process and improves compatibility with packaging standards. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_153 + +LANGUAGE: python +CODE: +``` +# Build system configuration update. +``` + +---------------------------------------- + +TITLE: boot_time() Suspend/Hibernation Handling on Windows +DESCRIPTION: Bug fix for psutil version 7.0.1: boot_time() on Windows now correctly accounts for time spent during suspend/hibernation. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_12 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to internal implementation. +``` + +---------------------------------------- + +TITLE: Process.create_time() and Clock Updates +DESCRIPTION: Bug fix for psutil version 7.0.1: Addressed issues where Process.create_time() did not reflect system clock updates on Linux, macOS, and NetBSD. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_9 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to internal implementation. +``` + +---------------------------------------- + +TITLE: iowait, guest, guest_nice Times Calculation +DESCRIPTION: Corrects the calculation of CPU times, specifically addressing the incorrect inclusion of 'iowait', 'guest', and 'guest_nice' times. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_313 + +LANGUAGE: python +CODE: +``` +from psutil import cpu_times + +# The cpu_times() function should now report these values more accurately. +# Example: +# times = cpu_times(percpu=True) +# for t in times: +# print(t) +``` + +---------------------------------------- + +TITLE: Process.open_files() and Process.connections() on macOS +DESCRIPTION: Fixes an issue on macOS where Process.open_files() and Process.connections() might raise an OSError without a specific error message if the process terminated. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_275 + +LANGUAGE: python +CODE: +``` +from psutil import Process, NoSuchProcess + +try: + p = Process() + open_files = p.open_files() + connections = p.connections() +except NoSuchProcess: + print("Process has terminated.") +except OSError as e: + print(f"OSError encountered: {e}") +``` + +---------------------------------------- + +TITLE: psutil Process Class Methods +DESCRIPTION: Details the methods available for controlling and querying process information using the psutil.Process class. This includes sending signals, terminating, killing, and retrieving various process attributes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_81 + +LANGUAGE: APIDOC +CODE: +``` +psutil.Process(pid) + Represents a running process. + + send_signal(signal): + Sends a signal to the process. + + terminate(): + Sends SIGTERM to the process. + + kill(): + Sends SIGKILL to the process. + + wait(timeout=None): + Wait for the process to terminate. Returns the exit code or signal. + On UNIX, returns negated signal number if terminated by signal. + On Windows, returns the exit code. + Raises psutil.TimeoutExpired if timeout is reached. + + name(): + Returns the process name. + + username(): + Returns the username of the process owner. + + communicate(): + Sends data to stdin and reads from stdout/stderr until EOF. + + as_dict(attrs=None, ad_value=None): + Returns process information as a dictionary. + + Example: + >>> import psutil + >>> p = psutil.Process() + >>> p.name() + 'python' + >>> p.terminate() + >>> p.wait() + +``` + +---------------------------------------- + +TITLE: Mounted Disk Partitions (disk_partitions()) +DESCRIPTION: Adds disk_partitions() to retrieve information about mounted disk partitions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_489 + +LANGUAGE: python +CODE: +``` +import psutil + +partitions = psutil.disk_partitions() +for p in partitions: + print(f'Device: {p.device}, Mountpoint: {p.mountpoint}, Fstype: {p.fstype}') +``` + +---------------------------------------- + +TITLE: net_connections() and Process.connections() Performance +DESCRIPTION: On Linux, net_connections() and Process.connections() are now up to 3x faster when dealing with a large number of connections, particularly on Python 2. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_334 + +LANGUAGE: python +CODE: +``` +psutil.net_connections() +``` + +LANGUAGE: python +CODE: +``` +process.connections() +``` + +---------------------------------------- + +TITLE: Process Network Connections +DESCRIPTION: Retrieves a list of network connections opened by a process. Supports filtering by internet protocol version and transport protocol. Includes file descriptor, address family, type, local/remote addresses, and status. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_76 + +LANGUAGE: APIDOC +CODE: +``` +.. method:: net_connections(kind="inet") + + Return socket connections opened by process as a list of named tuples. + To get system-wide connections use :func:`psutil.net_connections()`. + Every named tuple provides 6 attributes: + + - **fd**: the socket file descriptor. If the connection refers to the + current process this may be passed to `socket.fromfd`_ to obtain a usable + socket object. + On Windows, FreeBSD and SunOS this is always set to ``-1``. + - **family**: the address family, either `AF_INET`_, `AF_INET6`_ or + `AF_UNIX`_. + - **type**: the address type, either `SOCK_STREAM`_, `SOCK_DGRAM`_ or + `SOCK_SEQPACKET`_. . + - **laddr**: the local address as a ``(ip, port)`` named tuple or a ``path`` + in case of AF_UNIX sockets. For UNIX sockets see notes below. + - **raddr**: the remote address as a ``(ip, port)`` named tuple or an + absolute ``path`` in case of UNIX sockets. + When the remote endpoint is not connected you'll get an empty tuple + (AF_INET*) or ``""`` (AF_UNIX). For UNIX sockets see notes below. + - **status**: represents the status of a TCP connection. The return value + is one of the :data:`psutil.CONN_* ` constants. + For UDP and UNIX sockets this is always going to be + :const:`psutil.CONN_NONE`. + + The *kind* parameter is a string which filters for connections that fit the + following criteria: + + +----------------+-----------------------------------------------------+ + | **Kind value** | **Connections using** | + +================+=====================================================+ + | ``"inet"`` | IPv4 and IPv6 | + +----------------+-----------------------------------------------------+ + | ``"inet4"`` | IPv4 | + +----------------+-----------------------------------------------------+ + | ``"inet6"`` | IPv6 | + +----------------+-----------------------------------------------------+ + | ``"tcp"`` | TCP | + +----------------+-----------------------------------------------------+ + | ``"tcp4"`` | TCP over IPv4 | + +----------------+-----------------------------------------------------+ + | ``"tcp6"`` | TCP over IPv6 | + +----------------+-----------------------------------------------------+ + | ``"udp"`` | UDP | + +----------------+-----------------------------------------------------+ +``` + +---------------------------------------- + +TITLE: psutil API Documentation +DESCRIPTION: This section provides API documentation for psutil functions related to process management and system monitoring. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_458 + +LANGUAGE: APIDOC +CODE: +``` +Process.connections() + - Returns a list of network connections opened by the process. + - Supports UNIX domain sockets. + +Process.memory_info_ex() + - Returns per-process extended memory information. + - Platform specific. + +Process.exe() + - Returns the path to the executable of the process. + - On macOS, determined by asking the OS. + +Process.name() + - Returns the name of the process. + +Process.memory_info() + - Returns a tuple with memory usage statistics. + +Process.memory_percent() + - Returns memory usage percentage. + +Process.cpu_times() + - Returns a tuple with user and system CPU time. + +Process.cpu_percent(interval=None) + - Returns system-wide CPU utilization as a float. + - If interval is None, returns instantaneous percentage. + - If interval is a number, returns percentage over the interval. + +Process.num_threads() + - Returns the number of threads in the process. + +Process.num_ctx_switches() + - Returns the number of voluntary and involuntary context switches. + +Process.create_time() + - Returns the process creation time as a timestamp. + +Process.num_handles() + - Returns the number of handles opened by the process (Windows specific). + +Process.io_counters() + - Returns I/O statistics for the process. + +virtual_memory() + - Returns a tuple with system memory usage statistics (virtual memory). + +swap_memory() + - Returns a tuple with system swap memory usage statistics. + +net_io_counters(pernic=False) + - Returns system-wide network I/O statistics. + - If pernic is True, returns stats per network interface. + - Includes errin, errout, dropin, dropout fields. + +process_iter(attrs=None, ad_value=None) + - Returns an iterator yielding Process instances. + - Processes are sorted by PID. + +users() + - Returns a list of users currently connected on the system. + +disk_partitions(all=True) + - Returns a list of disk partitions. + - If all is False, excludes cd-rom, ramdisks and network mounts. + - Includes mount options. + +Process.children(recursive=False) + - Returns a list of direct children of the process. + - If recursive is True, returns all descendants. + +Process.wait(timeout=None) + - Wait for process to terminate. + - Consumes less CPU cycles. + +Process.as_dict(attrs=None, ad_value=None) + - Returns process information as a dictionary. + +Process.open_files() + - Returns a list of files opened by the process. + - Raises AccessDenied if permissions are insufficient. +``` + +---------------------------------------- + +TITLE: Linux Disk Partitions Path Handling +DESCRIPTION: Ensures that disk_partitions() on Linux correctly honors the PROCFS_PATH environment variable, allowing for custom procfs mount points. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_191 + +LANGUAGE: python +CODE: +``` +# [Linux]: disk_partitions() does not honour PROCFS_PATH. +``` + +---------------------------------------- + +TITLE: Process.open_files() Empty List Fix (Windows 10) +DESCRIPTION: Addresses an issue on Windows 10 where Process.open_files() might return an empty list incorrectly. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_298 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +p = Process() +open_files = p.open_files() +# This list should now be populated correctly on Windows 10. +``` + +---------------------------------------- + +TITLE: System-wide Open Connections (netstat-like) +DESCRIPTION: Adds functionality to retrieve system-wide open network connections, similar to the 'netstat' command. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_408 + +LANGUAGE: python +CODE: +``` +# Enhancement: system-wide open connections a-la "netstat" (add net_connections()). +# Implemented in psutil version 2.1.0 +``` + +---------------------------------------- + +TITLE: Process.environ() BSD Support +DESCRIPTION: Adds support for Process.environ() on BSD systems. This allows retrieving the environment variables of a process on BSD-based operating systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_92 + +LANGUAGE: APIDOC +CODE: +``` +Process.environ() + - Added support for BSD. + - Patch by Armin Gruner +``` + +---------------------------------------- + +TITLE: Find Processes by Name (Advanced) +DESCRIPTION: This advanced function searches for processes by matching the provided name against the process name, executable path, or command line. It offers a more robust way to find processes, especially when exact names might vary. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_94 + +LANGUAGE: python +CODE: +``` +import os +import psutil + +def find_procs_by_name(name): + """Return a list of processes matching 'name'.""" + ls = [] + for p in psutil.process_iter(["name", "exe", "cmdline"]): + if name == p.info['name'] or \ + p.info['exe'] and os.path.basename(p.info['exe']) == name or \ + p.info['cmdline'] and p.info['cmdline'][0] == name: + ls.append(p) + return ls +``` + +---------------------------------------- + +TITLE: PID 0 info retrieval on SunOS +DESCRIPTION: Fixes an issue on SunOS where querying basic information for PID 0 resulted in FileNotFoundError. This ensures that information for PID 0 can be retrieved. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_138 + +LANGUAGE: python +CODE: +``` +psutil.Process(0).name() +# Now works correctly on SunOS. +``` + +---------------------------------------- + +TITLE: Compilation Fixes for NetBSD +DESCRIPTION: Addresses critical compilation issues on NetBSD-5.x, ensuring psutil can be built successfully on this platform. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_293 + +LANGUAGE: python +CODE: +``` +# No direct code snippet, but ensures successful compilation: +# import psutil +# print("psutil compiled successfully on NetBSD") +``` + +---------------------------------------- + +TITLE: psutil General Bug Fixes and Platform Specifics +DESCRIPTION: General bug fixes and platform-specific improvements for psutil, addressing issues across Linux, NetBSD, Windows, and OpenBSD. Covers exceptions, process attributes, and utility functions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_45 + +LANGUAGE: APIDOC +CODE: +``` +General Fixes: +- 2195_, [Linux]: No longer print exception at import time if /proc/stat can't be read due to permissions; redirects to PSUTIL_DEBUG. +- 2241_, [NetBSD]: Compilation fix for NetBSD 10.99.3/amd64. +- 2245_, [Windows]: Fix unbound var error in swap_memory(). +- 2268_: bytes2human() utility function now correctly represents negative values. +- 2252_, [Windows]: Fix disk_usage() failure on Python 3.12+. +- 2284_, [Linux]: Process.memory_full_info() fallback to /proc/pid/smaps for ZombieProcess exceptions. +- 2287_, [OpenBSD], [NetBSD]: Process.is_running() correctly returns False for zombie processes. +- 2288_, [Linux]: Process.exe(), Process.cmdline(), Process.memory_maps() raise ZombieProcess instead of returning null values. +- 2290_: Clarified documentation regarding PID reuse checks for Process.nice(), Process.ionice(), Process.cpu_affinity(), Process.rlimit(), Process.parent(). +- 2308_, [OpenBSD]: Process.threads() fix for AccessDenied error. +``` + +---------------------------------------- + +TITLE: Process Constructor Enhancement +DESCRIPTION: The `Process` class constructor now automatically assumes `os.getpid()` if no argument is passed. This simplifies the creation of a `Process` object representing the current process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_446 + +LANGUAGE: python +CODE: +``` +import psutil + +# Previously required psutil.Process(os.getpid()) +# Now you can simply do: +p = psutil.Process() +print(f"Current process PID: {p.pid}") +``` + +---------------------------------------- + +TITLE: Process.rlimit() Linux Long Long Type Handling +DESCRIPTION: Fixes an issue on Linux where Process.rlimit() does not handle long long types properly. This ensures correct handling of large resource limits. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_97 + +LANGUAGE: APIDOC +CODE: +``` +Process.rlimit() + - Does not handle long long type properly on Linux. +``` + +---------------------------------------- + +TITLE: Process.boot_time() precision on Windows +DESCRIPTION: Increases the precision of Process.boot_time(), Process.create_time(), and users() login time on Windows to 1 microsecond. Previously, the precision was limited to 1 second. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_135 + +LANGUAGE: python +CODE: +``` +psutil.boot_time() +p.create_time() +# Now provides microsecond precision on Windows. +``` + +---------------------------------------- + +TITLE: Process.name() and Process.exe() Fix (Windows) +DESCRIPTION: Corrects erroneous return values and failures for Process.name() and Process.exe() on Windows by using QueryFullProcessImageNameW. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_166 + +LANGUAGE: python +CODE: +``` +Process.name() +Process.exe() +``` + +---------------------------------------- + +TITLE: Process Management Utilities +DESCRIPTION: Provides utilities for managing processes, including checking for process existence, retrieving a list of all process IDs, and iterating over processes. It also includes a psutil.Popen class for creating and managing child processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_560 + +LANGUAGE: APIDOC +CODE: +``` +pid_exists(pid) + Returns True if a process with the given PID exists, False otherwise. + +pids() + Returns a list of all process IDs currently running on the system. + +process_iter(attrs=None, ad_value=None) + Returns an iterator yielding Process instances for all running processes. + attrs: A list of attributes to prefetch for each process. + ad_value: Value to use for attributes that raise AccessDenied. + +psutil.Popen(*args, **kwargs) + A Popen subclass that integrates with psutil. + Allows for easier management and monitoring of child processes. + +``` + +---------------------------------------- + +TITLE: Windows 64-bit Support +DESCRIPTION: Adds support for Windows 64-bit systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_520 + +LANGUAGE: python +CODE: +``` +# psutil works on Windows 64-bit +``` + +---------------------------------------- + +TITLE: psutil HISTORY.rst Link +DESCRIPTION: Provides a link to the HISTORY.rst file, which contributors should update when making changes to the project. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/CONTRIBUTING.md#_snippet_2 + +LANGUAGE: markdown +CODE: +``` +[HISTORY.rst](https://github.com/giampaolo/psutil/blob/master/HISTORY.rst) +``` + +---------------------------------------- + +TITLE: Linux Process Children Access Denied Handling +DESCRIPTION: Fixes a scenario on Linux where Process.children() might inadvertently swallow AccessDenied exceptions, ensuring that permission errors are handled correctly. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_208 + +LANGUAGE: python +CODE: +``` +# [Linux]: there was a small chance Process.children() may swallow AccessDenied exceptions. +``` + +---------------------------------------- + +TITLE: Virtual Memory Information +DESCRIPTION: Retrieves system virtual memory statistics. Includes total, available, percent used, used, free, active, inactive, buffers, cached, shared, and slab memory. Note that 'used' + 'available' may not equal 'total'. On Windows, 'available' and 'free' are the same. Useful for cross-platform memory monitoring. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_10 + +LANGUAGE: APIDOC +CODE: +``` +virtual_memory() + Returns system virtual memory statistics as a named tuple. + Fields: + - total: Total physical memory in bytes. + - available: Memory available for new processes without swapping. + - percent: Percentage of memory used. + - used: Memory used by processes. + - free: Memory not used at all (zeroed). + - active: Memory currently in use or recently used. + - inactive: Memory marked as not used. + - buffers: Cache for file system metadata (Linux, BSD). + - cached: Cache for various things (Linux, BSD). + - shared: Memory accessible by multiple processes (Linux, BSD). + - slab: In-kernel data structures cache (Linux). + - wired: Memory that always stays in RAM (BSD, macOS). + Example: + >>> import psutil + >>> mem = psutil.virtual_memory() + >>> print(mem.available) + 6472179712 +``` + +---------------------------------------- + +TITLE: Process I/O Counters +DESCRIPTION: Introduces per-process I/O counters, allowing retrieval of read/write counts and bytes for a specific process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_492 + +LANGUAGE: python +CODE: +``` +p.io_counters() +``` + +---------------------------------------- + +TITLE: Process Signals +DESCRIPTION: This section briefly mentions the `signal` module, which is used for handling signals in Python processes. It provides a link to the official Python documentation for the module. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_115 + +LANGUAGE: APIDOC +CODE: +``` +signal module + - Provides a mechanism for handling asynchronous events on subprocesses. + - References: https://docs.python.org//library/signal.html + +``` + +---------------------------------------- + +TITLE: Process.cmdline() Zombie Process Fix +DESCRIPTION: On Linux, Process.cmdline() can now be more accurate in case of zombie processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_344 + +LANGUAGE: python +CODE: +``` +process.cmdline() +``` + +---------------------------------------- + +TITLE: getloadavg() calculation on Windows +DESCRIPTION: Corrects the mathematical calculation for 5 and 15-minute load averages returned by getloadavg() on Windows. This ensures accurate load average reporting. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_128 + +LANGUAGE: python +CODE: +``` +psutil.getloadavg() +# Load average calculations are now correct on Windows. +``` + +---------------------------------------- + +TITLE: Process Disappearance Exception Handling +DESCRIPTION: Ensures that properties like `ppid()`, `uids()`, `gids()`, `name()`, `exe()`, `cmdline()`, and `create_time()` correctly raise `NoSuchProcess` if the process disappears. These properties are no longer cached. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_534 + +LANGUAGE: python +CODE: +``` +p.ppid() +p.uids() +p.gids() +p.name() +p.exe() +p.cmdline() +p.create_time() +``` + +---------------------------------------- + +TITLE: System Memory Information Functions +DESCRIPTION: Adds get_phymem() and get_virtmem() functions to retrieve system memory information (total, used, free) and percentage usage. Deprecates older total_* and avail_* memory functions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_487 + +LANGUAGE: python +CODE: +``` +import psutil + +mem_info = psutil.virtual_memory() +print(f'Total memory: {mem_info.total}') +print(f'Available memory: {mem_info.available}') +print(f'Memory usage: {mem_info.percent}%') +``` + +---------------------------------------- + +TITLE: Swap Memory Information +DESCRIPTION: Retrieves system swap memory statistics. Includes total, used, free swap memory, percentage usage, and cumulative swap in/out bytes. On Windows, 'sin' and 'sout' are always 0. This function relies on /proc fs on Linux for container compatibility. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_11 + +LANGUAGE: APIDOC +CODE: +``` +swap_memory() + Returns system swap memory statistics as a named tuple. + Fields: + - total: Total swap memory in bytes. + - used: Used swap memory in bytes. + - free: Free swap memory in bytes. + - percent: Percentage usage of swap memory. + - sin: Cumulative bytes swapped in from disk. + - sout: Cumulative bytes swapped out to disk. + Example: + >>> import psutil + >>> psutil.swap_memory() + sswap(total=2097147904L, used=886620160L, free=1210527744L, percent=42.3, sin=1050411008, sout=1906720768) +``` + +---------------------------------------- + +TITLE: Process.username() Windows ERROR_NONE_MAPPED +DESCRIPTION: Fixes an issue on Windows where Process.username() may raise ERROR_NONE_MAPPED if the SID has no corresponding account name. Now, AccessDenied is raised in this case. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_89 + +LANGUAGE: APIDOC +CODE: +``` +Process.username() + - May raise ERROR_NONE_MAPPED if the SID has no corresponding account name. + - Now raises AccessDenied in this case. +``` + +---------------------------------------- + +TITLE: Enhancements in psutil 5.3.0 +DESCRIPTION: Details significant enhancements made in psutil version 5.3.0. This includes changes to disk_io_counters, net_io_counters, process connections, swap_memory, users, process iteration, unicode support, and disk_usage. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_217 + +LANGUAGE: python +CODE: +``` +Enhancements in psutil 5.3.0: +- `disk_io_counters()` and `net_io_counters()`: Introduced `nowrap` argument to prevent number wrapping. +- `net_connections()` and `Process.connections()`: `laddr` and `raddr` are now named tuples. +- `swap_memory()`: Now relies on `/proc/meminfo` for better compatibility with containers. +- `users()`: Provides a new `pid` field. +- `process_iter()`: Accepts `attrs` and `ad_value` for efficient process iteration. +- Implemented full unicode support. +- `disk_usage()`: Accepts bytes on Python 3. +- Test suite enables all warnings by default. +- Source distribution is dynamically generated. +- [FreeBSD]: `net_connections()` `fd` number is now set correctly. +- [SunOS]: Implemented `Process.environ()`. +``` + +---------------------------------------- + +TITLE: Process.open_files() OSError Handling on Linux +DESCRIPTION: Addresses rare conditions on Linux where Process.exe(), Process.open_files(), and Process.connections() could raise OSError(ESRCH) instead of NoSuchProcess. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_371 + +LANGUAGE: python +CODE: +``` +# Original issue: in rare conditions Process.exe(), Process.open_files() and Process.connections() can raise OSError(ESRCH) instead of NoSuchProcess_. +# Fix implemented in psutil version 2.1.2 +``` + +---------------------------------------- + +TITLE: PyPy support on Windows +DESCRIPTION: Adds support for running PyPy on Windows. This expands the platforms on which psutil can be used with PyPy. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_134 + +LANGUAGE: python +CODE: +``` +# Testing and compatibility improvements for PyPy on Windows. +``` + +---------------------------------------- + +TITLE: Process.open_files() Deleted File Handling +DESCRIPTION: On Linux, Process.open_files() now handles cases where deleted files are still visible, preventing failures. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_346 + +LANGUAGE: python +CODE: +``` +process.open_files() +``` + +---------------------------------------- + +TITLE: psutil 5.4.0 Enhancements and Bug Fixes +DESCRIPTION: Details enhancements and bug fixes for psutil version 5.4.0. Adds AIX platform support and fixes issues related to sensors_temperatures(), disk_io_counters(), Process.open_files(), sensors_fans(), compilation warnings, and Visual Studio compatibility. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_215 + +LANGUAGE: python +CODE: +``` +5.4.0 + +*2017-10-12* + +**Enhancements** + +- [AIX]: added support for AIX platform. + +**Bug fixes** + +- [Linux]: sensors_temperatures() may crash with IOError. +- [Windows]: disk_io_counters() "read_time" and "write_time" were expressed in tens of micro seconds instead of milliseconds. +- [macOS], **[critical]**: invalid reference counting in Process.open_files() may lead to segfault. +- [Linux]: sensors_fans() may crash with IOError. +- [SunOS]: fix compilation warnings. +- [Windows]: can't compile on newer versions of Visual Studio 2017 15.4. +- [Linux]: can't compile on CentOS 5.0 and RedHat 5.0. +``` + +---------------------------------------- + +TITLE: net_if_addrs() Enhancements +DESCRIPTION: The net_if_addrs() function now returns point-to-point (VPNs) addresses on POSIX systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_359 + +LANGUAGE: python +CODE: +``` +import psutil + +addresses = psutil.net_if_addrs() +for interface, addrs in addresses.items(): + for addr in addrs: + if addr.family == psutil.AF_LINK: # Example for point-to-point addresses + print(f"Interface: {interface}, Point-to-point address: {addr.address}") +``` + +---------------------------------------- + +TITLE: Process.exe() OSError Fix (FreeBSD) +DESCRIPTION: Resolves an OSError (ENOENT) that could occur when calling Process.exe() on FreeBSD. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_301 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +try: + p = Process() + exe_path = p.exe() + print(f"Executable path: {exe_path}") +except OSError as e: + print(f"Error getting executable path: {e}") +``` + +---------------------------------------- + +TITLE: net_io_counters() Fixes +DESCRIPTION: On FreeBSD, net_io_counters() dropout is no longer set to 0 if the kernel provides it. On SunOS, network interfaces are now detected correctly on Solaris 10. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_340 + +LANGUAGE: python +CODE: +``` +psutil.net_io_counters() +``` + +---------------------------------------- + +TITLE: Hardware Temperatures +DESCRIPTION: Retrieves hardware temperatures from the system. Supports Fahrenheit conversion and returns an empty dictionary if sensors are not supported. Available on Linux and FreeBSD. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_21 + +LANGUAGE: python +CODE: +``` +import psutil + +# Get temperatures in Celsius (default) +temps_celsius = psutil.sensors_temperatures() +print(f"Temperatures (Celsius): {temps_celsius}") + +# Get temperatures in Fahrenheit +temps_fahrenheit = psutil.sensors_temperatures(fahrenheit=True) +print(f"Temperatures (Fahrenheit): {temps_fahrenheit}") +``` + +---------------------------------------- + +TITLE: Process.open_files() AccessDenied Handling on Linux +DESCRIPTION: Fixes an issue on Linux where Process.open_files() might swallow AccessDenied exceptions, leading to an incomplete list of open files. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_372 + +LANGUAGE: python +CODE: +``` +# Original issue: Process.open_files() might swallow AccessDenied_ exceptions and return an incomplete list of open files on Linux. +# Fix implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: procinfo.py Script Update +DESCRIPTION: The accompanying procinfo.py script has been updated to provide significantly more information about processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_312 + +LANGUAGE: bash +CODE: +``` +# To use the updated script, ensure you have the latest psutil version. +# Then run the script from your terminal: +# python procinfo.py +``` + +---------------------------------------- + +TITLE: Process.children() and Process.parent() with Clock Updates +DESCRIPTION: Bug fix for psutil version 7.0.1: Ensured Process.children() and Process.parent() provide correct information when the system clock is updated. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_10 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to internal implementation. +``` + +---------------------------------------- + +TITLE: Process.name() Enhancement for Limited Users +DESCRIPTION: On Windows, Process.name() can now determine the process name even when running as a limited user. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_363 + +LANGUAGE: python +CODE: +``` +import psutil + +try: + # Iterate through all processes to demonstrate + for proc in psutil.process_iter(['pid', 'name']): + try: + print(f"PID: {proc.info['pid']}, Name: {proc.info['name']}") + except psutil.AccessDenied: + print(f"PID: {proc.info['pid']}, Name: ") +except Exception as e: + print(f"An error occurred: {e}") +``` + +---------------------------------------- + +TITLE: Windows Username Rewrite +DESCRIPTION: Rewrites `Process.username()` on Windows in pure C, removing WMI dependency and improving speed. No longer requires pywin32. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_523 + +LANGUAGE: python +CODE: +``` +p.username() +``` + +---------------------------------------- + +TITLE: API Changes in psutil 0.6.1 +DESCRIPTION: Details API modifications in psutil version 0.6.1, including changes to how Process.exe() handles symlinks and error conditions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_449 + +LANGUAGE: APIDOC +CODE: +``` +Process.exe(): + - can now return an empty string instead of raising AccessDenied. + - is no longer resolved in case it's a symlink. +``` + +---------------------------------------- + +TITLE: Testing Framework Update +DESCRIPTION: Adoption of 'tox' for running tests across multiple Python versions, improving test coverage and reliability. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_401 + +LANGUAGE: python +CODE: +``` +# Enhancement: use tox to run tests on multiple Python versions. +# Implemented in psutil version 2.1.2 +``` + +---------------------------------------- + +TITLE: Process Object Comparison +DESCRIPTION: Explains that `Process` objects can be compared for equality using the `==` operator. The comparison considers the PID, name, and command line of the processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_554 + +LANGUAGE: python +CODE: +``` +Process == Process +``` + +---------------------------------------- + +TITLE: Process Parent Information +DESCRIPTION: Explains how to access parent process information using `Process.parent()`, which returns a `Process` object for the parent, and `Process.ppid()`, which returns the parent's PID. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_550 + +LANGUAGE: python +CODE: +``` +Process.parent() +Process.ppid() +``` + +---------------------------------------- + +TITLE: Process.open_files() Windows Segfault Fix +DESCRIPTION: Addresses a critical bug on Windows where Process.open_files() may cause a segfault due to a NULL pointer. This fix prevents crashes when accessing open files. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_93 + +LANGUAGE: APIDOC +CODE: +``` +Process.open_files() + - May cause a segfault due to a NULL pointer on Windows. + - Critical bug fix. +``` + +---------------------------------------- + +TITLE: Find Processes by Name (Simple) +DESCRIPTION: This function iterates through all running processes and returns a list of psutil.Process objects whose name matches the provided name. It's a straightforward way to locate processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_93 + +LANGUAGE: python +CODE: +``` +import psutil + +def find_procs_by_name(name): + """Return a list of processes matching 'name'.""" + ls = [] + for p in psutil.process_iter(['name']): + if p.info['name'] == name: + ls.append(p) + return ls +``` + +---------------------------------------- + +TITLE: getloadavg() calculation on Windows +DESCRIPTION: Corrects the mathematical calculation for 5 and 15-minute load averages returned by getloadavg() on Windows. This ensures accurate load average reporting. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_157 + +LANGUAGE: python +CODE: +``` +psutil.getloadavg() +# Load average calculations are now correct on Windows. +``` + +---------------------------------------- + +TITLE: swap tests fail on Solaris +DESCRIPTION: Addresses failures in swap tests on Solaris when run by a normal user. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_414 + +LANGUAGE: python +CODE: +``` +# Original issue: swap tests fail on Solaris when run as normal user. +# Fix implemented in psutil version 2.1.0 +``` + +---------------------------------------- + +TITLE: Process.cpu_affinity() Enhancement +DESCRIPTION: Allows Process.cpu_affinity() to accept an empty list ('[]') as an argument to set the process affinity to all eligible CPUs. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_256 + +LANGUAGE: python +CODE: +``` +# Enhancement: Process.cpu_affinity() can now be passed [] argument as an alias to set affinity against all eligible CPUs. +# This simplifies setting CPU affinity to all available cores. +``` + +---------------------------------------- + +TITLE: Process.memory_percent() Parameter +DESCRIPTION: The Process.memory_percent() method now accepts a 'memtype' parameter, allowing for more specific memory usage reporting. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_327 + +LANGUAGE: python +CODE: +``` +process.memory_percent(memtype='rss') +``` + +---------------------------------------- + +TITLE: Windows Process I/O Nice Fix +DESCRIPTION: Corrects a mismatch in Process.ionice() on Windows systems, ensuring accurate reporting of I/O scheduling priorities. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_179 + +LANGUAGE: python +CODE: +``` +# [Windows]: fix Process.ionice() mismatch. +``` + +---------------------------------------- + +TITLE: net_io_counters() Wrap Fix on Windows +DESCRIPTION: Addresses an issue where net_io_counters() would wrap after 4G on Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_389 + +LANGUAGE: python +CODE: +``` +# Original issue: net_io_counters() wraps after 4G on Windows. +# Fix implemented in psutil version 2.1.1 +``` + +---------------------------------------- + +TITLE: Process Memory Information +DESCRIPTION: Covers methods for accessing process memory details, including `Process.memory_info()` for raw memory usage in bytes and `Process.memory_percent()` for memory utilization as a percentage. It also notes exceptions that might be raised on specific platforms. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_547 + +LANGUAGE: python +CODE: +``` +Process.memory_info() +Process.memory_percent() +``` + +---------------------------------------- + +TITLE: cpu_freq() Empty List Handling (Linux) +DESCRIPTION: Fixes an issue on Linux where cpu_freq() might return an empty list. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_233 + +LANGUAGE: python +CODE: +``` +# Original issue: [Linux]: cpu_freq() may return an empty list. +# This ensures cpu_freq() provides valid data when available. +``` + +---------------------------------------- + +TITLE: Bug Fixes in psutil 5.3.0 +DESCRIPTION: Details bug fixes implemented in psutil version 5.3.0. This covers issues related to boot_time, net_connections, Process class exceptions, disk and network I/O errors, unicode handling, access denied errors, memory leaks, and CPU count caching. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_218 + +LANGUAGE: python +CODE: +``` +Bug Fixes in psutil 5.3.0: +- [Windows]: `boot_time()` may return negative values or have fluctuations; caching implemented. +- [FreeBSD]: `net_connections()` may return incorrect PID. +- [Linux]: `Process` class exceptions handled correctly. +- `disk_io_counters()` and `net_io_counters()`: Raise `RuntimeError` on systems with no disks/NICs, and `TypeError` if no disks/NICs are installed. +- [macOS], [FreeBSD]: `Process.connections()` with `family=unix` handles unicode paths and `UnicodeDecodeError`. +- Memory leak fixed for `net_connections()` and `Process.connections()` with UNIX sockets. +- Fixed many unicode related issues, including `UnicodeDecodeError` and invalid encoded data. +- [FreeBSD]: psutil compilation issue on FreeBSD 12 resolved. +- [macOS]: `AccessDenied` errors for zombie processes corrected. +- [Windows]: `disk_partitions()` no longer overrides user's `SetErrorMode`. +- [Windows]: Memory leak in `Process.username()` fixed. +- [Windows]: `users()` `host` field corrected. +- [Windows]: Memory leak in `Process.memory_maps()` fixed. +- `cpu_count()` is no longer cached for runtime CPU changes. +- Fixed Python warnings. +- [NetBSD]: `net_connections()` may list incorrect sockets. +- [NetBSD]: `swap_memory()` segfault in case of error fixed. +- [OpenBSD]: `Process.cmdline()` `SystemError` fixed. +- [NetBSD]: `Process.cmdline()` memory leak fixed. +- [FreeBSD]: `Process.cpu_num()` corrected for kernel processes. +- [Linux]: `cpu_freq()` `IOError` on old RedHat distros fixed. +- [FreeBSD]: `sensors_battery()` `OSError` for no battery fixed. +- [Windows]: `net_if_addrs()` `inet_ntop()` return value checked. +- [SunOS]: `net_if_addrs()` shows correct addresses. +- [SunOS]: `net_connections()` works on SunOS 5.10. +- [FreeBSD]: `net_connections()` lists locally connected sockets. +- `cpu_count()` return value checked and forced to `None` if <= 1. +- `Process.cpu_percent()` guards against `cpu_count()` returning `None`. +- [SunOS]: `Process.memory_maps()` shows correct 64 bit addresses. +- [Windows]: `pid_exists()` behavior corrected. +``` + +---------------------------------------- + +TITLE: disk_usage() Percent Calculation +DESCRIPTION: Ensures the 'percent' field in disk_usage() correctly accounts for root-reserved space on POSIX systems, providing a more accurate disk usage percentage. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_288 + +LANGUAGE: python +CODE: +``` +from psutil import disk_usage + +usage = disk_usage('/') +print(f"Disk Usage Percentage: {usage.percent}") +``` + +---------------------------------------- + +TITLE: CI/test integration for PyPy on Travis +DESCRIPTION: Adds Continuous Integration and testing integration for PyPy on Travis CI. This ensures that psutil is tested against PyPy, improving compatibility and stability. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_133 + +LANGUAGE: python +CODE: +``` +# Travis CI configuration update for PyPy support. +``` + +---------------------------------------- + +TITLE: Run Tests in Parallel +DESCRIPTION: Executes tests in parallel using the make command for faster test execution. Requires the source code. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/psutil/tests/README.rst#_snippet_2 + +LANGUAGE: bash +CODE: +``` +make test-parallel +``` + +---------------------------------------- + +TITLE: API Changes in psutil 0.7.1 +DESCRIPTION: Details API modifications in psutil version 0.7.1, including changes to the Process.connections() method and renaming of network I/O functions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_447 + +LANGUAGE: APIDOC +CODE: +``` +Process.connections(): + - status field is no longer a string but a constant object (psutil.CONN_*). + - local_address and remote_address fields renamed to laddr and raddr. + +psutil.network_io_counters() renamed to net_io_counters(). +``` + +---------------------------------------- + +TITLE: Process.cpu_percent() Multicore Handling +DESCRIPTION: Fixes Process.cpu_percent() to correctly report percentages over 100 on multicore processors. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_480 + +LANGUAGE: python +CODE: +``` +# Corrected CPU percentage calculation for multicore systems. +``` + +---------------------------------------- + +TITLE: Import Error Fixes on Linux +DESCRIPTION: Addresses critical import errors on Linux, including issues with NUM_CPUS on ARM/SPARC and missing lines in /proc/meminfo on Debian 64-bit. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_483 + +LANGUAGE: python +CODE: +``` +# Fixes for critical import errors on Linux (ARM, SPARC, Debian 64-bit). +``` + +---------------------------------------- + +TITLE: PROCFS_PATH Constant +DESCRIPTION: The path to the /proc filesystem, primarily used on Linux, Solaris, and AIX. This constant defaults to "/proc" but can be reset if the /proc filesystem is mounted elsewhere or for accessing information within containers like Docker. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_91 + +LANGUAGE: python +CODE: +``` +import psutil + +# Default path +print(f"Default /proc path: {psutil.PROCFS_PATH}") + +# Example: If /proc is mounted at /host/proc +# psutil.PROCFS_PATH = "/host/proc" + +``` + +---------------------------------------- + +TITLE: Process Memory Maps +DESCRIPTION: Returns a list of the process's mapped memory regions. The structure of the returned named tuples varies by platform. If `grouped` is True, regions with the same path are aggregated. Otherwise, each region is listed individually with its address and permissions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_73 + +LANGUAGE: python +CODE: +``` +import psutil +p = psutil.Process() +# Get grouped memory maps +memory_maps_grouped = p.memory_maps(grouped=True) +# Get individual memory maps +memory_maps_individual = p.memory_maps(grouped=False) + +# Example Output (grouped): +# [pmmap_grouped(path='/lib/x86_64-linux-gnu/libutil-2.15.so', rss=32768, size=2125824, pss=32768, shared_clean=0, shared_dirty=0, private_clean=20480, private_dirty=12288, referenced=32768, anonymous=12288, swap=0), ...] +``` + +---------------------------------------- + +TITLE: Add cpu_freq() (Cross-platform) +DESCRIPTION: Introduces the cpu_freq() function to retrieve CPU frequency information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_254 + +LANGUAGE: python +CODE: +``` +# Enhancement: added cpu_freq() (CPU frequency). +# This function provides real-time CPU frequency data. +``` + +---------------------------------------- + +TITLE: Process.status() and Process.name() Speedup (Linux) +DESCRIPTION: Improves the performance of Process.status() by 28% and Process.name() by 25% on Linux through optimized /proc parsing. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_289 + +LANGUAGE: python +CODE: +``` +from psutil import Process +import time + +p = Process() + +start_time = time.time() +status = p.status() +print(f"Status: {status}, Time taken: {time.time() - start_time:.6f}s") + +start_time = time.time() +name = p.name() +print(f"Name: {name}, Time taken: {time.time() - start_time:.6f}s") +``` + +---------------------------------------- + +TITLE: FreeBSD virtual_memory() ENOMEM Error Fix +DESCRIPTION: Fixes a critical ENOMEM error in virtual_memory() on FreeBSD caused by a missing '#include ' directive. This ensures proper memory reporting. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_54 + +LANGUAGE: python +CODE: +``` +# Example of retrieving virtual memory statistics on FreeBSD +# import psutil +# try: +# mem = psutil.virtual_memory() +# print(f"Total: {mem.total}, Available: {mem.available}, Used: {mem.used}") +# except Exception as e: +# print(f"Error retrieving virtual memory: {e}") +``` + +---------------------------------------- + +TITLE: net_connections() Exception Handling on Linux +DESCRIPTION: Addresses exceptions related to net_connections() on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_391 + +LANGUAGE: python +CODE: +``` +# Original issue: net_connections() exceptions on Linux. +# Fix implemented in psutil version 2.1.1 +``` + +---------------------------------------- + +TITLE: Process.cmdline(), Process.environ() macOS EIO Error +DESCRIPTION: Handles EIO errors that may be raised on Process.cmdline() and Process.environ() on macOS. These errors are now translated into AccessDenied. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_90 + +LANGUAGE: APIDOC +CODE: +``` +Process.cmdline(), Process.environ() + - EIO error may be raised on macOS. + - Now translated into AccessDenied. +``` + +---------------------------------------- + +TITLE: Process.exe() Windows AccessDenied Fix +DESCRIPTION: On Windows, Process.exe() will now succeed for all process PIDs instead of raising AccessDenied. This improves the reliability of retrieving executable paths. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_98 + +LANGUAGE: APIDOC +CODE: +``` +Process.exe() + - Will succeed for all process PIDs (instead of raising AccessDenied) on Windows. +``` + +---------------------------------------- + +TITLE: Bug Fixes in psutil +DESCRIPTION: This snippet summarizes critical bug fixes in psutil, including memory leaks in `Process.num_fds()`, potential heap corruption in `Process.num_threads()` and `Process.status()`, and compilation issues on FreeBSD. It also addresses incorrect return values for `net_io_counters()` and permission-related errors. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_453 + +LANGUAGE: python +CODE: +``` +# Memory leak fixes +Process.num_fds() +# Heap corruption fixes +Process.num_threads(), Process.status() +# Compilation fixes +# Incorrect return values +net_io_counters() +# Permission errors +Process.open_files() +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes and Enhancements (Version 5.9.3) +DESCRIPTION: Details bug fixes and enhancements for psutil version 5.9.3, specifically for macOS. Includes fixes for net_connections() and provision of arm64 wheels. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_44 + +LANGUAGE: APIDOC +CODE: +``` +Enhancements: +- 2040_, [macOS]: Provide wheels for arm64 architecture. + +Bug fixes: +- 2116_, [macOS], [critical]: net_connections() fix for RuntimeError. +``` + +---------------------------------------- + +TITLE: API Change: Process.connections() Status Strings +DESCRIPTION: The `status` strings returned by `Process.connections()` are now represented as constants, improving readability and maintainability when checking connection states. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_444 + +LANGUAGE: python +CODE: +``` +import psutil + +# Example: Iterating through connections and checking status +# for conn in psutil.net_connections(): +# if conn.status == psutil.CONN_CLOSE_WAIT: +# print(f"Connection in CLOSE_WAIT state: {conn}") +``` + +---------------------------------------- + +TITLE: disk_io_counters() Metrics Update +DESCRIPTION: On NetBSD, disk_io_counters() metrics now update correctly. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_357 + +LANGUAGE: python +CODE: +``` +psutil.disk_io_counters() +``` + +---------------------------------------- + +TITLE: Disk I/O Counters +DESCRIPTION: Retrieves system-wide disk I/O statistics. Can return per-disk statistics if perdisk is True. Handles potential integer overflows with the nowrap argument. Requires 'diskperf -y' on Windows to enable counters. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_15 + +LANGUAGE: python +CODE: +``` +import psutil + +# Get system-wide disk I/O counters +print(psutil.disk_io_counters()) + +# Get per-disk I/O counters +print(psutil.disk_io_counters(perdisk=True)) +``` + +---------------------------------------- + +TITLE: psutil.net_if_addrs() - Network Interface Addresses +DESCRIPTION: Retrieves addresses associated with each network interface card (NIC). Returns a dictionary where keys are NIC names and values are lists of named tuples, each containing address family, address, netmask, broadcast, and ptp information. Platform-specific notes apply regarding UNIX sockets and Windows support for broadcast/ptp fields. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_19 + +LANGUAGE: python +CODE: +``` +import psutil + +# Get network interface addresses +addresses = psutil.net_if_addrs() +print(addresses) + +# Example output structure: +# { +# 'lo': [ +# snicaddr(family=, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None), +# snicaddr(family=, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None), +# snicaddr(family=, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None) +# ], +# 'wlan0': [ +# snicaddr(family=, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None), +# snicaddr(family=, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None), +# snicaddr(family=, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None) +# ] +# } +``` + +---------------------------------------- + +TITLE: Process.cmdline() ZombieProcess error on NetBSD +DESCRIPTION: Corrects an issue on NetBSD where Process.cmdline() could erroneously raise a ZombieProcess error if the command line contained non-encodable characters. This ensures proper error handling for such cases. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_155 + +LANGUAGE: python +CODE: +``` +p.cmdline() +# Now handles non-encodable characters without raising ZombieProcess. +``` + +---------------------------------------- + +TITLE: psutil Process Network Connections +DESCRIPTION: Retrieves a list of network connections for the process. The `net_connections` method returns a list of named tuples, each representing a connection with details like file descriptor, address family, socket type, local address, remote address, and status. Platform-specific notes apply to UNIX sockets. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_77 + +LANGUAGE: python +CODE: +``` +import psutil + +p = psutil.Process(1694) +connections = p.net_connections() +print(connections) +``` + +---------------------------------------- + +TITLE: Process.cpu_times() and memory_maps() on SunOS +DESCRIPTION: Addresses a RuntimeError on SunOS when querying 64-bit processes with a 32-bit Python interpreter for methods like cpu_times(), cpu_percent(), threads(), and memory_maps(). Null values are returned as a fallback. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_276 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +try: + p = Process() + cpu_times = p.cpu_times() + memory_maps = p.memory_maps() + # ... other methods +except RuntimeError as e: + print(f"RuntimeError encountered (likely 32/64-bit mismatch): {e}") + # Fallback to null values or handle appropriately +``` + +---------------------------------------- + +TITLE: Windows Process Attribute Bitness Handling +DESCRIPTION: On Windows, Process.cmdline() and Process.cwd() now correctly handle cases where the bitness of psutil and the target process differ. This prevents incorrect results or AccessDenied errors. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_331 + +LANGUAGE: python +CODE: +``` +process.cmdline() +``` + +LANGUAGE: python +CODE: +``` +process.cwd() +``` + +---------------------------------------- + +TITLE: Process.open_files() Fix for Large PIDs on Windows +DESCRIPTION: Corrects an issue with Process.open_files() on Windows where it failed for Process IDs (PIDs) greater than 64K. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_369 + +LANGUAGE: python +CODE: +``` +# Original issue: fixed Process.open_files() for PID > 64K on Windows. +# Fix implemented in psutil version 2.1.0 +``` + +---------------------------------------- + +TITLE: PID Reuse Checking for ppid() and parents() +DESCRIPTION: PID reuse is now preemptively checked for Process.ppid() and Process.parents(). This ensures that the parent process ID and parent process information returned are accurate, even if the original process has been recycled. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_40 + +LANGUAGE: python +CODE: +``` +try: + ppid = proc.ppid() + parents = proc.parents() + print(f"Parent PID: {ppid}") + print(f"Parent processes: {parents}") +except psutil.NoSuchProcess: + print("Process no longer exists.") +``` + +---------------------------------------- + +TITLE: disk_partitions() on BSD +DESCRIPTION: Corrects the behavior of disk_partitions() on BSD systems when all=False is specified. Previously, it returned an empty list; now, it ignores the argument and returns all partitions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_273 + +LANGUAGE: python +CODE: +``` +from psutil import disk_partitions + +# This call will now return all partitions, ignoring all=False +partitions = disk_partitions(all=False) +print(partitions) +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes and Enhancements (Version 5.9.5) +DESCRIPTION: Details bug fixes and enhancements for psutil version 5.9.5, covering various platforms like Linux, NetBSD, Windows, and OpenBSD. Includes improvements to exception handling, process information retrieval, and network connection reporting. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_42 + +LANGUAGE: APIDOC +CODE: +``` +Enhancements: +- 2196_: Cleaner error traceback by hiding KeyError from missed cache hits. +- 2217_: Print full traceback for DeprecationWarning or UserWarning. +- 2230_, [OpenBSD]: Rewritten net_connections() to retrieve AF_UNIX socket paths, improve speed, and avoid duplicate entries. +- 2238_, [UNIX]: Consolidated Process.cwd() return value to "" for non-existent directories. +- 2239_, [UNIX]: Improved Process.name() handling for zombie processes with truncated names. +- 2240_, [NetBSD], [OpenBSD]: Added CI testing for NetBSD and OpenBSD platforms (Python 3 only). + +Bug fixes: +- 1043_, [OpenBSD] net_connections() duplicate entries. +- 1915_, [Linux]: Approximation for available memory when /proc/meminfo returns 0. +- 2164_, [Linux]: Compilation fix for kernels < 2.6.27. +- 2186_, [FreeBSD]: Compilation fix with Clang 15. +- 2191_, [Linux]: disk_partitions() avoids unnecessary /proc/filesystems read unless all=False. +- 2216_, [Windows]: Test fixes for virtual environments. +- 2225_, [POSIX]: users() started attribute precision fix (off by 1 minute). +- 2229_, [OpenBSD]: zombie process recognition fix, preventing NoSuchProcess instead of ZombieProcess. +- 2231_, [NetBSD]: virtual_memory() available metric corrected. +- 2234_, [NetBSD]: virtual_memory() metrics corrected to match htop. +- 2236_, [NetBSD]: Process.num_threads() and Process.threads() exclude terminated threads. +- 2237_, [OpenBSD], [NetBSD]: Process.cwd() returns "" for non-existent directories instead of FileNotFoundError. +``` + +---------------------------------------- + +TITLE: Process.cmdline() ZombieProcess error on NetBSD +DESCRIPTION: Corrects an issue on NetBSD where Process.cmdline() could erroneously raise a ZombieProcess error if the command line contained non-encodable characters. This ensures proper error handling for such cases. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_126 + +LANGUAGE: python +CODE: +``` +p.cmdline() +# Now handles non-encodable characters without raising ZombieProcess. +``` + +---------------------------------------- + +TITLE: psutil 5.4.2 Enhancements and Bug Fixes +DESCRIPTION: Details enhancements and bug fixes for psutil version 5.4.2. Introduces PSUTIL_DEBUG environment variable, adds macOS battery support, improves Process.children() speed, and deprecates Process.memory_info_ex(). Includes fixes for disk_io_counters(), users(), Process.cmdline(), Process.memory_maps(), and pids(). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_213 + +LANGUAGE: python +CODE: +``` +5.4.2 + +*2017-12-07* + +**Enhancements** + +- introduced PSUTIL_DEBUG environment variable which can be set in order to print useful debug messages on stderr (useful in case of nasty errors). +- [macOS]: added support for sensors_battery(). +- Process.children() is 2x faster on POSIX and 2.4x faster on Linux. +- deprecated method Process.memory_info_ex() now warns by using FutureWarning instead of DeprecationWarning. + +**Bug fixes** + +- [Windows]: disk_io_counters() may return an empty dict. +- [Linux]: users() hostname returns username instead. +- [Windows]: make test does not work. +- [Linux]: Process.cmdline() is now able to split cmdline args for misbehaving processes which overwrite /proc/pid/cmdline and use spaces instead of null bytes as args separator. +- [macOS]: Process.memory_maps() may raise ENOENT. +- [macOS]: pids() does not return PID 0 on recent macOS versions. +``` + +---------------------------------------- + +TITLE: PROCFS_PATH Constant Exposure +DESCRIPTION: The PROCFS_PATH constant is now exposed, allowing users to change the default location of the /proc filesystem on systems where it is applicable (e.g., Linux, SunOS). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_351 + +LANGUAGE: python +CODE: +``` +psutil.PROCFS_PATH = '/path/to/proc' +``` + +---------------------------------------- + +TITLE: Process.open_files() Speed on AIX +DESCRIPTION: Bug fix for psutil version 6.1.0: Significantly improved the speed of Process.open_files() for some edge cases on AIX. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_32 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to internal implementation. +``` + +---------------------------------------- + +TITLE: psutil 5.4.1 Enhancements and Bug Fixes +DESCRIPTION: Details enhancements and bug fixes for psutil version 5.4.1. Adds AIX support for Process.num_ctx_switches() and drops Python 3.3 support. Includes fixes for process termination exit codes on Windows and compilation issues on AIX and Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_214 + +LANGUAGE: python +CODE: +``` +5.4.1 + +*2017-11-08* + +**Enhancements** + +- [AIX]: add support for Process.num_ctx_switches(). +- drop Python 3.3 support (psutil still works but it's no longer tested). + +**Bug fixes** + +- [Windows]: when a process is terminated now the exit code is set to SIGTERM instead of 0. +- python -m psutil.tests fail. +- [AIX], **[critical]**: psutil won't compile on AIX 6.1.0. +- [Windows]: net_io_counters() packets count now include also non-unicast packets. +``` + +---------------------------------------- + +TITLE: Process Status Exception Handling +DESCRIPTION: Fixes an issue where `Process.status()` could raise an unhandled exception. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_537 + +LANGUAGE: python +CODE: +``` +p.status() +``` + +---------------------------------------- + +TITLE: Network I/O Counters (net_io_counters()) +DESCRIPTION: Introduces network I/O counters via the net_io_counters() function. Patches provided by Jeremy Whitlock for macOS and Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_474 + +LANGUAGE: python +CODE: +``` +import psutil + +net_io = psutil.net_io_counters() +print(f'Bytes sent: {net_io.bytes_sent}') +print(f'Bytes received: {net_io.bytes_recv}') +``` + +---------------------------------------- + +TITLE: Per-Process Network Connections +DESCRIPTION: Adds retrieval of per-process opened TCP and UDP connections. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_519 + +LANGUAGE: python +CODE: +``` +p.connections() +``` + +---------------------------------------- + +TITLE: swap_memory() Robustness +DESCRIPTION: On Linux, swap_memory() no longer crashes if 'sin' or 'sout' cannot be determined due to a missing '/proc/vmstat'. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_338 + +LANGUAGE: python +CODE: +``` +psutil.swap_memory() +``` + +---------------------------------------- + +TITLE: Process UID and GID +DESCRIPTION: Details the `Process.uid` and `Process.gid` properties, which return the User ID and Group ID of a process, respectively. This feature is supported on macOS and Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_549 + +LANGUAGE: python +CODE: +``` +Process.uid +Process.gid +``` + +---------------------------------------- + +TITLE: Networking and Socket Operations +DESCRIPTION: This section covers network-related functionalities, including socket types and operations like `socket.fromfd`. It references Python's socket module documentation. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_114 + +LANGUAGE: APIDOC +CODE: +``` +SOCK_DGRAM + - Represents a datagram socket (UDP). + +SOCK_STREAM + - Represents a stream socket (TCP). + +SOCK_SEQPACKET + - Represents a sequenced packet socket. + +socket.fromfd(fd, family, type, proto=0) + - Create a socket object from a file descriptor. + - Parameters: + - fd: The file descriptor. + - family: The address family (e.g., socket.AF_INET). + - type: The socket type (e.g., socket.SOCK_STREAM). + - proto: The protocol (defaults to 0). + - Returns: A socket object. + +``` + +LANGUAGE: python +CODE: +``` +import socket + +# Example of socket types +print(f"SOCK_DGRAM: {socket.SOCK_DGRAM}") +print(f"SOCK_STREAM: {socket.SOCK_STREAM}") +print(f"SOCK_SEQPACKET: {socket.SOCK_SEQPACKET}") + +# Conceptual usage of socket.fromfd (requires an existing file descriptor) +# try: +# # Assume 'existing_fd' is a valid file descriptor obtained elsewhere +# existing_fd = 10 # Placeholder +# s = socket.fromfd(existing_fd, socket.AF_INET, socket.SOCK_STREAM) +# print(f"Socket created from fd: {s}") +# except OSError as e: +# print(f"Error creating socket from fd: {e}") + +``` + +---------------------------------------- + +TITLE: Linux Process Status Enhancement +DESCRIPTION: Adds the psutil.STATUS_PARKED constant for Process.status() on Linux, allowing for the recognition and reporting of 'parked' process states. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_196 + +LANGUAGE: python +CODE: +``` +# [Linux]: added "psutil.STATUS_PARKED" constant for Process.status(). +``` + +---------------------------------------- + +TITLE: psutil Support for OpenBSD +DESCRIPTION: Added support for OpenBSD operating system, including necessary fixes for compilation and functionality. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_350 + +LANGUAGE: python +CODE: +``` +# OpenBSD support example (no specific code snippet) +``` + +---------------------------------------- + +TITLE: Process CPU Times +DESCRIPTION: Returns a named tuple with accumulated user and system CPU times for the process, in seconds. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_60 + +LANGUAGE: python +CODE: +``` +import psutil + +p = psutil.Process() + +# Get CPU times +print(p.cpu_times()) +``` + +---------------------------------------- + +TITLE: Network Connections +DESCRIPTION: Returns a list of system-wide socket connections. Connections can be filtered by kind (e.g., 'inet', 'tcp', 'udp', 'unix'). On macOS and AIX, root privileges are required. For per-process connections, use `Process.net_connections`. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_18 + +LANGUAGE: APIDOC +CODE: +``` +psutil.net_connections(kind='inet') + + Return system-wide socket connections as a list of named tuples. + Every named tuple provides 7 attributes: + + - **fd**: the socket file descriptor. If the connection refers to the current + process this may be passed to `socket.fromfd`_ to obtain a usable socket object. + On Windows and SunOS this is always set to ``-1``. + - **family**: the address family, either `AF_INET`_, `AF_INET6`_ or `AF_UNIX`_. + - **type**: the address type, either `SOCK_STREAM`_, `SOCK_DGRAM`_ or + `SOCK_SEQPACKET`_. + - **laddr**: the local address as a ``(ip, port)`` named tuple or a ``path`` + in case of AF_UNIX sockets. For UNIX sockets see notes below. + - **raddr**: the remote address as a ``(ip, port)`` named tuple or an + absolute ``path`` in case of UNIX sockets. + When the remote endpoint is not connected you'll get an empty tuple + (AF_INET*) or ``""`` (AF_UNIX). For UNIX sockets see notes below. + - **status**: represents the status of a TCP connection. The return value + is one of the `psutil.CONN_* <#connections-constants>`_ constants + (a string). + For UDP and UNIX sockets this is always going to be + :const:`psutil.CONN_NONE`. + - **pid**: the PID of the process which opened the socket, if retrievable, + else ``None``. On some platforms (e.g. Linux) the availability of this + field changes depending on process privileges (root is needed). + + The *kind* parameter is a string which filters for connections matching the + following criteria: + + .. table:: + + +----------------+-----------------------------------------------------+ + | **Kind value** | **Connections using** | + +================+=====================================================+ + | ``"inet"`` | IPv4 and IPv6 | + +----------------+-----------------------------------------------------+ + | ``"inet4"`` | IPv4 | + +----------------+-----------------------------------------------------+ + | ``"inet6"`` | IPv6 | + +----------------+-----------------------------------------------------+ + | ``"tcp"`` | TCP | + +----------------+-----------------------------------------------------+ + | ``"tcp4"`` | TCP over IPv4 | + +----------------+-----------------------------------------------------+ + | ``"tcp6"`` | TCP over IPv6 | + +----------------+-----------------------------------------------------+ + | ``"udp"`` | UDP | + +----------------+-----------------------------------------------------+ + | ``"udp4"`` | UDP over IPv4 | + +----------------+-----------------------------------------------------+ + | ``"udp6"`` | UDP over IPv6 | + +----------------+-----------------------------------------------------+ + | ``"unix"`` | UNIX socket (both UDP and TCP protocols) | + +----------------+-----------------------------------------------------+ + | ``"all"`` | the sum of all the possible families and protocols | + +----------------+-----------------------------------------------------+ + + On macOS and AIX this function requires root privileges. + To get per-process connections use :meth:`Process.net_connections`. + Also, see `netstat.py`_ example script. + Example: + + >>> import psutil + >>> psutil.net_connections() + [pconn(fd=115, family=, type=, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED', pid=1254), + pconn(fd=117, family=, type=, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING', pid=2987), +``` + +---------------------------------------- + +TITLE: Exception Handling for Nonexistent Processes +DESCRIPTION: Describes the behavior of `NoSuchProcess` exception, which is raised when attempting to access information for a process that no longer exists or was not found during creation. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_551 + +LANGUAGE: python +CODE: +``` +NoSuchProcess +``` + +---------------------------------------- + +TITLE: Process User and Group Information +DESCRIPTION: Retrieves user and group identifiers for the process. `username()` returns the process owner's name. `uids()` returns real, effective, and saved user IDs. `gids()` returns real, effective, and saved group IDs. These methods are primarily available on UNIX systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_48 + +LANGUAGE: APIDOC +CODE: +``` +.. method:: username() + + The name of the user that owns the process. On UNIX this is calculated by + using real process uid. + +.. method:: uids() + + The real, effective and saved user ids of this process as a named tuple. + This is the same as `os.getresuid`_ but can be used for any process PID. + + Availability: UNIX + +.. method:: gids() + + The real, effective and saved group ids of this process as a named tuple. + This is the same as `os.getresgid`_ but can be used for any process PID. + + Availability: UNIX +``` + +---------------------------------------- + +TITLE: Process.cwd() and other Windows process info errors +DESCRIPTION: Addresses critical issues on Windows where Process.cmdline(), Process.environ(), or Process.cwd() could fail with ERROR_PARTIAL_COPY. This error is now correctly translated to AccessDenied. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_110 + +LANGUAGE: python +CODE: +``` +p.cwd() +# Now correctly raises AccessDenied instead of ERROR_PARTIAL_COPY. +``` + +---------------------------------------- + +TITLE: boot_time() Precision Issue on macOS +DESCRIPTION: Bug fix for psutil version 7.0.1: Corrected a 45-second offset in boot_time() on macOS due to a C precision issue. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_8 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to internal implementation. +``` + +---------------------------------------- + +TITLE: Process.suspend() and Process.resume() Optimization (Windows) +DESCRIPTION: Optimizes process suspension and resumption on Windows by using NtSuspendProcess and NtResumeProcess, leading to faster and more reliable operations. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_163 + +LANGUAGE: python +CODE: +``` +Process.suspend() +Process.resume() +``` + +---------------------------------------- + +TITLE: Process Suspend/Resume Exception Handling (Windows Fix) +DESCRIPTION: Fixes a critical bug on Windows where `WindowsError` was raised instead of `AccessDenied` for `Process.resume()` and `Process.suspend()`. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_506 + +LANGUAGE: python +CODE: +``` +p.resume() +p.suspend() +``` + +---------------------------------------- + +TITLE: Process.open_files() rewrite on Windows +DESCRIPTION: Provides a complete rewrite and error checking for Process.open_files() on Windows. This improves the reliability and accuracy of retrieving the list of open files for a process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_112 + +LANGUAGE: python +CODE: +``` +p.open_files() +# Now more robust and handles errors correctly. +``` + +---------------------------------------- + +TITLE: CPU Percent Interval Parameter +DESCRIPTION: Allows the `cpu_percent()` and `Process.cpu_percent()` functions to accept an `interval` parameter for non-blocking usage. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_525 + +LANGUAGE: python +CODE: +``` +psutil.cpu_percent(interval=1) +p.cpu_percent(interval=1) +``` + +---------------------------------------- + +TITLE: Process.environ() Enhancement +DESCRIPTION: The Process.environ() method has been added, allowing access to a process's environment variables. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_326 + +LANGUAGE: python +CODE: +``` +process.environ() +``` + +---------------------------------------- + +TITLE: Process Memory Stats (USS and PSS) +DESCRIPTION: On Linux, psutil now provides 'real' memory statistics using Unique Set Size (USS) and Proportional Set Size (PSS) for processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_353 + +LANGUAGE: python +CODE: +``` +process.memory_info() +``` + +---------------------------------------- + +TITLE: psutil 5.3.1 Bug Fixes +DESCRIPTION: Details bug fixes for psutil version 5.3.1, specifically mentioning the relocation of documentation. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_216 + +LANGUAGE: python +CODE: +``` +5.3.1 + +*2017-09-10* + +**Enhancements** + +- documentation moved to http://psutil.readthedocs.io + +**Bug fixes** + +- +``` + +---------------------------------------- + +TITLE: Process.open_files() rewrite on Windows +DESCRIPTION: Provides a complete rewrite and error checking for Process.open_files() on Windows. This improves the reliability and accuracy of retrieving the list of open files for a process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_141 + +LANGUAGE: python +CODE: +``` +p.open_files() +# Now more robust and handles errors correctly. +``` + +---------------------------------------- + +TITLE: Process Memory Information +DESCRIPTION: Returns memory information for the process, including 'rss' (Resident Set Size) and 'vms' (Virtual Memory Size). Fields may vary by platform. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_66 + +LANGUAGE: python +CODE: +``` +import psutil +p = psutil.Process() +print(p.memory_info()) +``` + +---------------------------------------- + +TITLE: virtual_memory() Precision on Linux +DESCRIPTION: Improves the precision of 'available' and 'used' memory values returned by virtual_memory() on Linux, making them consistent with the 'free' command. 'available' now correctly accounts for LCX containers. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_284 + +LANGUAGE: python +CODE: +``` +from psutil import virtual_memory + +vmem = virtual_memory() +print(f"Available Memory: {vmem.available}") +print(f"Used Memory: {vmem.used}") +``` + +---------------------------------------- + +TITLE: Process.connections() Renamed to Process.net_connections() +DESCRIPTION: The Process.connections() method has been renamed to Process.net_connections() for clarity. The old name is still available but deprecated and will trigger a DeprecationWarning. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_35 + +LANGUAGE: python +CODE: +``` +# New method (recommended) +connections = proc.net_connections() + +# Old method (deprecated) +# connections = proc.connections() +``` + +---------------------------------------- + +TITLE: psutil Support for NetBSD +DESCRIPTION: Added support for NetBSD operating system, including necessary fixes for compilation and functionality. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_349 + +LANGUAGE: python +CODE: +``` +# NetBSD support example (no specific code snippet) +``` + +---------------------------------------- + +TITLE: FreeBSD Compilation Fix +DESCRIPTION: Fixes psutil compilation issues against FreeBSD 6.x. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_529 + +LANGUAGE: python +CODE: +``` +# psutil now compiles correctly on FreeBSD 6.x. +``` + +---------------------------------------- + +TITLE: Process.name() String Truncation on Linux +DESCRIPTION: Fixes an issue on Linux where Process.name() could truncate strings containing spaces or parentheses. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_413 + +LANGUAGE: python +CODE: +``` +# Original issue: Process.name() truncates string in case it contains spaces or parentheses on Linux. +# Fix implemented in psutil version 2.1.0 +``` + +---------------------------------------- + +TITLE: Process Kill Method +DESCRIPTION: Describes the `Process.kill()` method for terminating a process. It notes specific behaviors and exception handling, particularly for PID 0 on Windows, where it now raises `AccessDenied`. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_555 + +LANGUAGE: python +CODE: +``` +Process.kill() +``` + +---------------------------------------- + +TITLE: Vulture CLI Tool Usage +DESCRIPTION: Enhancement for psutil version 6.1.1: Utilized the Vulture CLI tool to detect dead code. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_22 + +LANGUAGE: bash +CODE: +``` +vulture . +``` + +---------------------------------------- + +TITLE: Process CPU Times +DESCRIPTION: Changes `Process.cpu_times()` to return a namedtuple instead of a tuple. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_518 + +LANGUAGE: APIDOC +CODE: +``` +Process: + cpu_times(): Returns CPU times as a namedtuple (user, system). +``` + +---------------------------------------- + +TITLE: Process I/O Counters +DESCRIPTION: Retrieves process I/O statistics, including read/write counts and bytes. Specific fields like 'read_chars', 'write_chars', 'other_count', and 'other_bytes' are platform-dependent (Linux and Windows). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_54 + +LANGUAGE: python +CODE: +``` +import psutil + +p = psutil.Process() + +# Get I/O counters +io_counters = p.io_counters() +print(io_counters) +``` + +---------------------------------------- + +TITLE: Process.nice() Deprecation and Alternatives +DESCRIPTION: The Process.nice property is deprecated. Use get_nice() and set_nice() methods instead for better clarity and control over process niceness. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_459 + +LANGUAGE: python +CODE: +``` +# Deprecated: +# process.nice = 10 + +# Recommended: +process.set_nice(10) +niceness = process.get_nice() +``` + +---------------------------------------- + +TITLE: Exception Message Enhancement +DESCRIPTION: Includes process name and PID in exception messages. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_522 + +LANGUAGE: APIDOC +CODE: +``` +Exceptions: + Exception messages now include process name and PID for better context. +``` + +---------------------------------------- + +TITLE: Dropped FreeBSD 8 Support +DESCRIPTION: Compatibility note for psutil version 7.0.1: Dropped support for FreeBSD 8 and earlier versions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_1 + +LANGUAGE: python +CODE: +``` +# No specific code snippet available for this compatibility change. +``` + +---------------------------------------- + +TITLE: Process CPU Number +DESCRIPTION: Returns the CPU number the process is currently running on. Availability: Linux, FreeBSD, SunOS. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_65 + +LANGUAGE: python +CODE: +``` +import psutil +p = psutil.Process() +print(p.cpu_num()) +``` + +---------------------------------------- + +TITLE: Process.children() Enhancement +DESCRIPTION: This snippet describes the addition of the `recursive=True` parameter to `Process.children()`, enabling it to return all process descendants. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_456 + +LANGUAGE: python +CODE: +``` +Process.children(recursive=True) # Return all process descendants +``` + +---------------------------------------- + +TITLE: Process Creation Time +DESCRIPTION: Retrieves the process creation time as seconds since the epoch. The value is cached and based on the system clock, which can be affected by time adjustments. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_41 + +LANGUAGE: python +CODE: +``` +import psutil +import datetime + +p = psutil.Process() + +# Get creation time +create_time_seconds = p.create_time() +print(f"Creation time (seconds since epoch): {create_time_seconds}") + +# Convert to human-readable format +create_time_dt = datetime.datetime.fromtimestamp(create_time_seconds) +print(f"Creation time (datetime): {create_time_dt.strftime('%Y-%m-%d %H:%M:%S')}") +``` + +---------------------------------------- + +TITLE: Windows Process Command Line Access +DESCRIPTION: On Windows versions 8.1 and later, this addresses an issue where Process.cmdline() might fail with ERROR_ACCESS_DENIED. It implements a fallback mechanism using NtQueryInformationProcess with ProcessCommandLineInformation to retrieve the command line. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_171 + +LANGUAGE: python +CODE: +``` +# On Windows >= 8.1 if Process.cmdline() fails due to ERROR_ACCESS_DENIED +# attempt using NtQueryInformationProcess + ProcessCommandLineInformation. +``` + +---------------------------------------- + +TITLE: net_connections() UNIX Socket Handling on Linux +DESCRIPTION: Fixes an issue on Linux where net_connections() might skip some legitimate UNIX sockets. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_390 + +LANGUAGE: python +CODE: +``` +# Original issue: net_connections() might skip some legitimate UNIX sockets on Linux. +# Fix implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: Process.cpu_affinity() Segfault Fix on FreeBSD +DESCRIPTION: Addresses a critical segfault issue on FreeBSD when setting Process.cpu_affinity() with an invalid CPU number. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_366 + +LANGUAGE: python +CODE: +``` +# Original issue: Process.cpu_affinity() segfaults on set in case an invalid CPU number is provided. +# Fix implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: net_connections() Malformed Data Handling +DESCRIPTION: On Linux, net_connections() can now handle malformed '/proc/net/unix' files, preventing crashes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_342 + +LANGUAGE: python +CODE: +``` +psutil.net_connections() +``` + +---------------------------------------- + +TITLE: Network I/O Counters +DESCRIPTION: Retrieves system-wide network I/O statistics. The `pernic` argument allows fetching counters for each network interface individually. The numbers no longer wrap across calls since version 5.3.0. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_17 + +LANGUAGE: python +CODE: +``` +import psutil + +# Get system-wide network I/O counters +print(psutil.net_io_counters()) + +# Get network I/O counters per network interface +print(psutil.net_io_counters(pernic=True)) +``` + +---------------------------------------- + +TITLE: Compilation Warnings Fix (macOS/BSD) +DESCRIPTION: Resolves numerous compilation warnings encountered on macOS and BSD systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_317 + +LANGUAGE: python +CODE: +``` +# No direct code snippet, but ensures cleaner builds: +# import psutil +# print("psutil compiled cleanly.") +``` + +---------------------------------------- + +TITLE: Process.environ() and Process.cwd() AccessDenied on Windows +DESCRIPTION: Fixes critical issues on Windows where Process.cmdline(), Process.environ(), or Process.cwd() could fail with ERROR_PARTIAL_COPY. This error is now correctly translated to AccessDenied. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_154 + +LANGUAGE: python +CODE: +``` +p.environ() +p.cwd() +# Now correctly raises AccessDenied instead of ERROR_PARTIAL_COPY. +``` + +---------------------------------------- + +TITLE: Compilation fix for source distribution on Windows +DESCRIPTION: Corrects a critical C syntax error in the source distribution that prevented compilation on Windows. This ensures that users can build psutil from source on Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_120 + +LANGUAGE: python +CODE: +``` +# Fixes compilation errors in setup.py or C extensions. +``` + +---------------------------------------- + +TITLE: Process.environ() and Process.cwd() AccessDenied on Windows +DESCRIPTION: Fixes critical issues on Windows where Process.cmdline(), Process.environ(), or Process.cwd() could fail with ERROR_PARTIAL_COPY. This error is now correctly translated to AccessDenied. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_125 + +LANGUAGE: python +CODE: +``` +p.environ() +p.cwd() +# Now correctly raises AccessDenied instead of ERROR_PARTIAL_COPY. +``` + +---------------------------------------- + +TITLE: Process.oneshot() Cache Handling +DESCRIPTION: Resolves a critical issue in Process.oneshot() where incorrect cache handling could lead to Process instances returning inaccurate results. This fix ensures data integrity. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_181 + +LANGUAGE: python +CODE: +``` +# [critical]: incorrect handling of cache in Process.oneshot() context causes Process instances to return incorrect results. +``` + +---------------------------------------- + +TITLE: Linux Process Status Recognition +DESCRIPTION: Enhances Process.status() on Linux to correctly recognize and report 'idle' and 'parked' process states, which were previously returned as '?'. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_203 + +LANGUAGE: python +CODE: +``` +# [Linux]: Process.status() is unable to recognize "idle" and "parked" statuses (returns "?"). +``` + +---------------------------------------- + +TITLE: Process.cwd() Behavior for Terminated Processes +DESCRIPTION: On NetBSD, if a process terminates, Process.cwd() will now return an empty string instead of raising a NoSuchProcess exception. This provides a more consistent behavior for accessing the current working directory of potentially defunct processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_37 + +LANGUAGE: python +CODE: +``` +try: + cwd = proc.cwd() +except psutil.NoSuchProcess: + cwd = "" + print("Process terminated, returning empty string for cwd.") +``` + +---------------------------------------- + +TITLE: Process CPU Times +DESCRIPTION: Details the `Process.cpu_times()` method for retrieving per-process CPU user and kernel times. This functionality was enhanced to correctly handle dead processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_546 + +LANGUAGE: python +CODE: +``` +Process.cpu_times() +``` + +---------------------------------------- + +TITLE: Usage percent rounding on Python 2 +DESCRIPTION: Fixes an issue where usage percentages could be rounded to 0 on Python 2. This ensures more accurate reporting of resource utilization. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_127 + +LANGUAGE: python +CODE: +``` +p.cpu_percent() +# Usage percentages are now more accurate on Python 2. +``` + +---------------------------------------- + +TITLE: Process Context Switches +DESCRIPTION: Returns the number of voluntary and involuntary context switches performed by the process. This count is cumulative. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_55 + +LANGUAGE: python +CODE: +``` +import psutil + +p = psutil.Process() + +# Get context switch count +print(p.num_ctx_switches()) +``` + +---------------------------------------- + +TITLE: cpu_affinity() EINVAL Handling on Linux +DESCRIPTION: Fixes an issue on Linux where cpu_affinity() might return EINVAL. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_382 + +LANGUAGE: python +CODE: +``` +# Original issue: Process.cpu_affinity() might return EINVAL on Linux. +# Fix implemented in psutil version 2.1.2 +``` + +---------------------------------------- + +TITLE: Process Iteration and Scripting Additions +DESCRIPTION: This snippet covers changes related to process iteration and the addition of new utility scripts. It notes that `process_iter()` now yields processes sorted by PID and mentions the inclusion of `pmap.py` and `netstat.py` scripts. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_452 + +LANGUAGE: python +CODE: +``` +process_iter() # Yields processes sorted by PID +pmap.py # New script for process memory maps +netstat.py # New script for network statistics +``` + +---------------------------------------- + +TITLE: NtWow64* syscall error handling on Windows +DESCRIPTION: Fixes an issue on Windows where NtWow64* syscalls failed to raise the proper error code. This improves the error handling for low-level Windows API calls. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_130 + +LANGUAGE: python +CODE: +``` +# Internal Windows API call error handling improved. +``` + +---------------------------------------- + +TITLE: Python 3.6 64-bit Wheel Compatibility (Windows) +DESCRIPTION: Fixes compatibility issues with the uploaded wheels for Python 3.6 64-bit on Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_260 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Windows]: the uploaded wheels for Python 3.6 64 bit didn't work. +# This ensures proper installation and functionality on Windows with Python 3.6 64-bit. +``` + +---------------------------------------- + +TITLE: Compilation fix for source distribution on Windows +DESCRIPTION: Corrects a critical C syntax error in the source distribution that prevented compilation on Windows. This ensures that users can build psutil from source on Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_149 + +LANGUAGE: python +CODE: +``` +# Fixes compilation errors in setup.py or C extensions. +``` + +---------------------------------------- + +TITLE: Process.cmdline() and Process.exe() error handling on Windows +DESCRIPTION: Resolves unhandled exceptions ('WinError 1168 element not found') that occurred in Process.cmdline() and Process.exe() on Windows 10 for specific pseudo processes like 'Registry' and 'Memory Compression'. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_109 + +LANGUAGE: python +CODE: +``` +p.cmdline() +p.exe() +# These operations are now more robust on Windows 10. +``` + +---------------------------------------- + +TITLE: NtWow64* syscall error handling on Windows +DESCRIPTION: Fixes an issue on Windows where NtWow64* syscalls failed to raise the proper error code. This improves the error handling for low-level Windows API calls. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_159 + +LANGUAGE: python +CODE: +``` +# Internal Windows API call error handling improved. +``` + +---------------------------------------- + +TITLE: Process.username() KeyError Handling on POSIX +DESCRIPTION: Corrects a potential KeyError in Process.username() on POSIX systems if the UID cannot be resolved. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_373 + +LANGUAGE: python +CODE: +``` +# Original issue: Process.username() may raise KeyError if UID can't be resolved on POSIX. +# Fix implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: psutil Namespace for Tests +DESCRIPTION: Tests are now organized within the psutil namespace, improving code structure and maintainability. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_354 + +LANGUAGE: python +CODE: +``` +# Test organization example (no specific code snippet) +``` + +---------------------------------------- + +TITLE: SetSeDebug() Handle and Impersonation Fix on Windows +DESCRIPTION: Fixes SetSeDebug() on Windows to correctly close handles and unset impersonation upon return. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_491 + +LANGUAGE: python +CODE: +``` +# Fix for SetSeDebug() handle and impersonation issues on Windows. +``` + +---------------------------------------- + +TITLE: Deprecated Process.memory_info_ex() Removed +DESCRIPTION: Compatibility note for psutil version 7.0.0: The long-deprecated Process.memory_info_ex() method has been removed. Use Process.memory_full_info() instead. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_19 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +# process = Process() +# memory_info = process.memory_full_info() +``` + +---------------------------------------- + +TITLE: Network Connection State Constants +DESCRIPTION: Constants representing the state of a network connection, as returned by psutil.net_connections(). These cover various TCP states like CONN_ESTABLISHED, CONN_CLOSE_WAIT, CONN_LISTEN, and platform-specific states. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_90 + +LANGUAGE: python +CODE: +``` +import psutil + +for conn in psutil.net_connections(kind='inet4'): + if conn.status == psutil.CONN_ESTABLISHED: + print(f"Established connection: {conn.laddr} -> {conn.raddr}") + elif conn.status == psutil.CONN_LISTEN: + print(f"Listening on port: {conn.laddr.port}") +# ... handle other connection states +``` + +---------------------------------------- + +TITLE: Windows OpenProcess Access Rights +DESCRIPTION: Enhances security and reduces access denied exceptions on Windows by using PROCESS_QUERY_LIMITED_INFORMATION access rights with OpenProcess whenever possible. This is particularly beneficial for system processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_182 + +LANGUAGE: python +CODE: +``` +# [Windows]: OpenProcess now uses PROCESS_QUERY_LIMITED_INFORMATION access rights wherever possible, resulting in less AccessDenied exceptions being thrown for system processes. +``` + +---------------------------------------- + +TITLE: Process Status +DESCRIPTION: Retrieves the current status of the process as a string. The returned string corresponds to one of the `psutil.STATUS_*` constants. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_46 + +LANGUAGE: APIDOC +CODE: +``` +.. method:: status() + + The current process status as a string. The returned string is one of the + `psutil.STATUS_* <#process-status-constants>`_ constants. +``` + +---------------------------------------- + +TITLE: Windows Service Handling (Unicode) +DESCRIPTION: Improves handling of Unicode service names and descriptions for Windows services, ensuring compatibility with non-ASCII characters. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_279 + +LANGUAGE: python +CODE: +``` +from psutil import win_service_iter + +for svc in win_service_iter(): + # Accessing unicode names and descriptions should now work correctly + print(f"Service Name: {svc.name}, Description: {svc.description}") +``` + +---------------------------------------- + +TITLE: psutil.net_if_stats() - Network Interface Statistics +DESCRIPTION: Retrieves statistics for each network interface card (NIC). Returns a dictionary where keys are NIC names and values are named tuples containing 'isup' (status), 'duplex' (communication type), 'speed' (in Mbps), 'mtu' (maximum transmission unit), and 'flags' (interface flags). The 'flags' field is available on UNIX systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_20 + +LANGUAGE: python +CODE: +``` +import psutil + +# Get network interface statistics +stats = psutil.net_if_stats() +print(stats) + +# Example output structure: +# { +# 'eth0': snicstats(isup=True, duplex=, speed=100, mtu=1500, flags='up,broadcast,running,multicast') +# } +``` + +---------------------------------------- + +TITLE: net_io_counters() on Windows Vista+ +DESCRIPTION: Fixes value wrapping in net_io_counters() on Windows Vista (NT 6.0) and above by using 64-bit values from newer Windows APIs, preventing data loss for high network traffic. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_281 + +LANGUAGE: python +CODE: +``` +from psutil import net_io_counters + +stats = net_io_counters() +print(f"Bytes Sent: {stats.bytes_sent}, Bytes Received: {stats.bytes_recv}") +# Values should now be accurate even for high traffic +``` + +---------------------------------------- + +TITLE: Process Information Enhancements +DESCRIPTION: This snippet details enhancements to the Process class in psutil, including support for UNIX sockets, extended memory information, and improved process path determination on macOS. It also covers performance improvements and bug fixes related to access permissions and speed. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_450 + +LANGUAGE: python +CODE: +``` +Process.connections() # UNIX sockets support +Process.memory_info_ex() # per-process extended memory info +Process.exe() # improved path determination on macOS +Process.name(), Process.memory_info(), Process.memory_percent(), Process.cpu_times(), Process.cpu_percent(), Process.num_threads() # Faster and no AccessDenied for non-current processes on macOS +Process.num_ctx_switches() # per-process number of voluntary and involuntary context switches +Process.create_time(), Process.cpu_times(), Process.cpu_percent(), Process.memory_info(), Process.memory_percent(), Process.num_handles(), Process.io_counters() # No AccessDenied for non-owned processes on Windows +``` + +---------------------------------------- + +TITLE: SunOS Network Connections Fix +DESCRIPTION: Corrects an issue on SunOS where net_connections() would return an empty list, ensuring that network connection information is properly retrieved. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_194 + +LANGUAGE: python +CODE: +``` +# [SunOS]: net_connections() returns an empty list. +``` + +---------------------------------------- + +TITLE: disk_partitions() Exposes maxfile and maxpath +DESCRIPTION: Enhances disk_partitions() to expose two extra fields: maxfile and maxpath, representing the maximum file name and path name length, respectively. This provides additional information about disk partition limits. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_87 + +LANGUAGE: APIDOC +CODE: +``` +disk_partitions() + - Exposes two extra fields: maxfile and maxpath. + - maxfile: Maximum file name length. + - maxpath: Maximum path name length. +``` + +---------------------------------------- + +TITLE: Unsupported Windows XP Error Message +DESCRIPTION: Provides a more informative error message when attempting to use psutil on unsupported versions of Windows XP. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_265 + +LANGUAGE: python +CODE: +``` +# Enhancement: [Windows]: provide a more meaningful error message if trying to use psutil on unsupported Windows XP. +# This improves user experience by clearly indicating unsupported platform usage. +``` + +---------------------------------------- + +TITLE: Process.is_running() Speedup and PID Reuse Handling +DESCRIPTION: Process.is_running() is sped up by caching its return value. It also now correctly checks if a PID has been reused, preventing false positives. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_461 + +LANGUAGE: python +CODE: +``` +# Caching return value for performance +# Checking for PID reuse to ensure accuracy +``` + +---------------------------------------- + +TITLE: Process.memory_maps() Performance +DESCRIPTION: On Linux, Process.memory_maps() is now slightly faster. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_335 + +LANGUAGE: python +CODE: +``` +process.memory_maps() +``` + +---------------------------------------- + +TITLE: New cpu_stats() Function +DESCRIPTION: A new function, cpu_stats(), has been introduced. It returns statistics about CPU context switches, interrupts, soft interrupts, and system calls. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_324 + +LANGUAGE: python +CODE: +``` +psutil.cpu_stats() +``` + +---------------------------------------- + +TITLE: procsmem.py Script +DESCRIPTION: A new script named procsmem.py has been added, likely for process memory analysis or related utilities. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_355 + +LANGUAGE: python +CODE: +``` +procsmem.py +``` + +---------------------------------------- + +TITLE: Add Process.cpu_num() (Windows/Linux/macOS) +DESCRIPTION: Introduces Process.cpu_num() to determine which CPU a process is currently running on. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_252 + +LANGUAGE: python +CODE: +``` +# Enhancement: added Process.cpu_num() (what CPU a process is on). +# This function provides information about the CPU affinity of a process. +``` + +---------------------------------------- + +TITLE: Process.cmdline() handling on Linux +DESCRIPTION: Enhances Process.cmdline() on Linux to correctly handle misbehaving processes that rename their command line or use inappropriate characters for argument separation. This ensures more reliable retrieval of process command-line arguments. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_101 + +LANGUAGE: python +CODE: +``` +p.cmdline() +# Previously, this could fail or return corrupted data for certain processes. +``` + +---------------------------------------- + +TITLE: Process.memory_full_info() Fix (Windows) +DESCRIPTION: Fixes a segfault in Process.memory_full_info() on Windows by using NtQueryVirtualMemory for USS memory calculation. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_165 + +LANGUAGE: python +CODE: +``` +Process.memory_full_info() +``` + +---------------------------------------- + +TITLE: Usage percent rounding on Python 2 +DESCRIPTION: Fixes an issue where usage percentages could be rounded to 0 on Python 2. This ensures more accurate reporting of resource utilization. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_156 + +LANGUAGE: python +CODE: +``` +p.cpu_percent() +# Usage percentages are now more accurate on Python 2. +``` + +---------------------------------------- + +TITLE: pid_exists() Zombie Process Handling (Linux) +DESCRIPTION: Fixes pid_exists() on Linux to no longer return True for thread IDs, ensuring it only checks for process existence. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_257 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Linux]: pid_exists() no longer returns True if passed a process thread ID. +# This ensures pid_exists() correctly identifies running processes. +``` + +---------------------------------------- + +TITLE: Process.num_fds() for POSIX Systems +DESCRIPTION: Introduces Process.num_fds() for POSIX systems to retrieve the number of opened file descriptors for a process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_462 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +p = Process() +num_fds = p.num_fds() +``` + +---------------------------------------- + +TITLE: psutil.STATUS_* Constants Comparison +DESCRIPTION: psutil.STATUS_* constants can now be compared using their string representations. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_470 + +LANGUAGE: python +CODE: +``` +if process.status() == psutil.STATUS_RUNNING: + print('Process is running.') + +# Or using string representation: +if str(process.status()) == 'running': + print('Process is running (string comparison).') +``` + +---------------------------------------- + +TITLE: Linux Disk I/O Counters Dual Implementation +DESCRIPTION: Introduces a dual implementation for disk_io_counters() on Linux, which relies on the /sys/block filesystem as a fallback when /proc/diskstats is unavailable. This enhances robustness, especially on systems like Raspberry Pi. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_197 + +LANGUAGE: python +CODE: +``` +# [Linux]: add disk_io_counters() dual implementation relying on /sys/block filesystem in case /proc/diskstats is not available. +``` + +---------------------------------------- + +TITLE: Process Handles (Windows) +DESCRIPTION: Returns the number of handles currently used by the process. This count is not cumulative and is specific to Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_57 + +LANGUAGE: python +CODE: +``` +import psutil + +p = psutil.Process() + +# Get number of handles (Windows only) +print(p.num_handles()) +``` + +---------------------------------------- + +TITLE: NetBSD swap_memory() Calculation Correction +DESCRIPTION: Corrects miscalculations in swap_memory() on NetBSD, ensuring accurate reporting of swap space usage. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_55 + +LANGUAGE: python +CODE: +``` +# Example of retrieving swap memory statistics on NetBSD +# import psutil +# try: +# swap = psutil.swap_memory() +# print(f"Total: {swap.total}, Used: {swap.used}, Free: {swap.free}") +# except Exception as e: +# print(f"Error retrieving swap memory: {e}") +``` + +---------------------------------------- + +TITLE: CPU Times Exception Handling +DESCRIPTION: Prevents exceptions from being printed during import time if cpu_times() fails, improving the user experience during library initialization. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_187 + +LANGUAGE: python +CODE: +``` +# do not print exception on import time in case cpu_times() fails. +``` + +---------------------------------------- + +TITLE: Windows 2000 Support +DESCRIPTION: Adds support for Windows 2000. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_524 + +LANGUAGE: python +CODE: +``` +# psutil works on Windows 2000 +``` + +---------------------------------------- + +TITLE: Process Status Constants +DESCRIPTION: Constants representing the status of a process, as returned by psutil.Process.status(). These include states like running, sleeping, stopped, zombie, and more, with some platform-specific additions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_85 + +LANGUAGE: python +CODE: +``` +import psutil + +process = psutil.Process(pid) +status = process.status() + +if status == psutil.STATUS_RUNNING: + print(f"Process {pid} is running.") +elif status == psutil.STATUS_SLEEPING: + print(f"Process {pid} is sleeping.") +# ... handle other statuses +``` + +---------------------------------------- + +TITLE: Per-Process Working Directory +DESCRIPTION: Introduces the `Process.cwd()` method for retrieving the current working directory of a process. This feature is noted as being available on Linux and Windows platforms. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_544 + +LANGUAGE: python +CODE: +``` +Process.cwd() +``` + +---------------------------------------- + +TITLE: psutil Exceptions +DESCRIPTION: Details the exceptions raised by the psutil library, specifically AccessDenied and TimeoutExpired, which indicate permission issues or timeouts during process operations. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_30 + +LANGUAGE: APIDOC +CODE: +``` +.. class:: AccessDenied(pid=None, name=None, msg=None) + Raised by :class:`Process` class methods when permission to perform an + action is denied due to insufficient privileges. + *name* attribute is available if :meth:`Process.name()` was previously called. + +.. class:: TimeoutExpired(seconds, pid=None, name=None, msg=None) + Raised by :meth:`Process.wait` method if timeout expires and the process is + still alive. + *name* attribute is available if :meth:`Process.name()` was previously called. +``` + +---------------------------------------- + +TITLE: System Information Functions +DESCRIPTION: Provides access to system-wide information such as disk usage, network statistics, CPU load, and memory status. These functions offer a way to monitor the overall health and performance of the system. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_559 + +LANGUAGE: APIDOC +CODE: +``` +disk_usage(path) + Returns disk usage statistics for the given path. + path: The path to check. + Returns: A named tuple with total, used, and free disk space. + +getloadavg() + Returns the system load average as a tuple of three floats. + +net_connections() + Returns a list of all network connections on the system. + +net_if_addrs() + Returns a dictionary of network interface addresses. + +net_if_stats() + Returns network interface statistics. + +net_io_counters(pernic=False, nowrap=True) + Returns system-wide network I/O statistics. + pernic: If True, return stats per network interface. + nowrap: If True, prevent wraparound at 2^64. + +sensors_battery() + Returns battery status information. + +sensors_fans() + Returns fan speed information. + +sensors_temperatures() + Returns system temperature information. + +swap_memory() + Returns swap memory information. + +users() + Returns a list of users currently logged into the system. + +virtual_memory() + Returns virtual memory statistics. + +wait_procs(pid, timeout=None, callback=None) + Waits for a process to complete. + pid: The PID of the process to wait for. + timeout: Maximum time to wait in seconds. + callback: A function to call with the process object when it finishes. + +win_service_get(name) + Returns a Windows service object by name. + name: The name of the service. + +win_service_iter() + Returns an iterator over all installed Windows services. + +``` + +---------------------------------------- + +TITLE: Process.ionice() and Process.nice() Enum Support +DESCRIPTION: On Python >= 3.4, IOPRIO_CLASS_* and *_PRIORITY_CLASS constants returned by Process.ionice() and Process.nice() are now enums instead of plain integers. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_361 + +LANGUAGE: python +CODE: +``` +import psutil +import sys + +if sys.version_info >= (3, 4): + try: + p = psutil.Process() + # Example for ionice + priority_class = p.ionice().priority_class + print(f"I/O Priority Class: {priority_class}") + + # Example for nice + nice_value = p.nice() + print(f"Nice Value: {nice_value}") + + except psutil.AccessDenied: + print("Access denied to process information.") +else: + print("Enum support for nice/ionice requires Python 3.4+") +``` + +---------------------------------------- + +TITLE: Process File Descriptors (UNIX) +DESCRIPTION: Returns the number of file descriptors currently opened by the process. This count is not cumulative and is available on UNIX-like systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_56 + +LANGUAGE: python +CODE: +``` +import psutil + +p = psutil.Process() + +# Get number of open file descriptors +print(p.num_fds()) +``` + +---------------------------------------- + +TITLE: Process Send Signal and Terminate +DESCRIPTION: Adds methods to send signals to a process and to terminate it. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_515 + +LANGUAGE: python +CODE: +``` +p.send_signal(signal.SIGTERM) +p.terminate() +``` + +---------------------------------------- + +TITLE: pip Compatibility for Windows Wheels +DESCRIPTION: Resolves incompatibility issues between psutil's Windows wheels and pip version 7.1.2. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_295 + +LANGUAGE: bash +CODE: +``` +# Ensure you are using a compatible pip version: +# pip install --upgrade pip +# Then install psutil: +# pip install psutil +``` + +---------------------------------------- + +TITLE: Disk Usage +DESCRIPTION: Returns disk usage statistics for the partition containing the given path. Includes total, used, and free space in bytes, along with the percentage of usage. Raises OSError if the path does not exist. This functionality is also available as `shutil.disk_usage` since Python 3.3. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_13 + +LANGUAGE: APIDOC +CODE: +``` +disk_usage(path) + Returns disk usage statistics for the partition containing the given path. + Parameters: + - path (str): The path to check disk usage for. + Returns: + A named tuple with the following fields: + - total: Total partition size in bytes. + - used: Used space in bytes. + - free: Free space in bytes. + - percent: Percentage of disk usage. + Raises: + OSError: If the path does not exist. + Example: + >>> import psutil + >>> psutil.disk_usage('/') + sdiskusage(total=100000000000, used=50000000000, free=50000000000, percent=50.0) +``` + +---------------------------------------- + +TITLE: Compilation Fix for Solaris +DESCRIPTION: Addresses a critical issue preventing psutil from compiling on Solaris. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_308 + +LANGUAGE: python +CODE: +``` +# No direct code snippet, but ensures successful compilation: +# import psutil +# print("psutil compiled successfully on Solaris") +``` + +---------------------------------------- + +TITLE: Disk I/O Counters (disk_io_counters()) +DESCRIPTION: Introduces disk I/O counters via the disk_io_counters() function. Patches provided by Jeremy Whitlock for macOS and Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_477 + +LANGUAGE: python +CODE: +``` +import psutil + +disk_io = psutil.disk_io_counters() +print(f'Read count: {disk_io.read_count}') +print(f'Write count: {disk_io.write_count}') +``` + +---------------------------------------- + +TITLE: Linux Process Memory Maps and I/O Counters +DESCRIPTION: Addresses an issue where Process.memory_maps() and Process.io_counters() methods were exposed even when not supported by the Linux kernel. These methods are now conditionally exposed based on kernel support. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_178 + +LANGUAGE: python +CODE: +``` +# [Linux]: Process.memory_maps() and Process.io_counters() methods are no longer exposed if not supported by the kernel. +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes and Enhancements (Version 5.9.4) +DESCRIPTION: Details bug fixes and enhancements for psutil version 5.9.4, focusing on Windows and Linux platforms. Includes improvements to virtual memory reporting and compilation compatibility. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_43 + +LANGUAGE: APIDOC +CODE: +``` +Enhancements: +- 2102_: Use Limited API for wheels with CPython 3.6+ on Linux, macOS, and Windows for future compatibility. + +Bug fixes: +- 2077_, [Windows]: Use system-level values for virtual_memory(). +- 2156_, [Linux]: Compilation fix for old gcc compilers missing SPEED_UNKNOWN definition. +- 2010_, [macOS]: Fix build failure on macOS arm64 where IFM_1000_TX and IFM_1000_T were the same. +- 2160_, [Windows]: Get Windows percent swap usage from performance counters. +``` + +---------------------------------------- + +TITLE: Import Error Fix on FreeBSD +DESCRIPTION: Resolves critical import time crashes on FreeBSD 7 and minor versions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_484 + +LANGUAGE: python +CODE: +``` +# Fix for critical import time crashes on FreeBSD. +``` + +---------------------------------------- + +TITLE: Process.open_files() Race Condition Fix on Linux +DESCRIPTION: Addresses a potential race condition in Process.open_files() on Linux that could lead to NoSuchProcess exceptions or incorrect path names. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_466 + +LANGUAGE: python +CODE: +``` +# Fix for race condition in Process.open_files() on Linux. +``` + +---------------------------------------- + +TITLE: psutil Process Class +DESCRIPTION: Represents an operating system process identified by a PID. It handles process-specific operations and provides methods for accessing process information efficiently. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_31 + +LANGUAGE: APIDOC +CODE: +``` +.. class:: Process(pid=None) + Represents an OS process with the given *pid*. + If *pid* is omitted current process *pid* (`os.getpid`_) is used. + Raise :class:`NoSuchProcess` if *pid* does not exist. + On Linux *pid* can also refer to a thread ID (the *id* field returned by + :meth:`threads` method). + When accessing methods of this class always be prepared to catch + :class:`NoSuchProcess` and :class:`AccessDenied` exceptions. + `hash`_ builtin can be used against instances of this class in order to + identify a process univocally over time (the hash is determined by mixing + process PID + creation time). As such it can also be used with `set`_. + + .. note:: + + In order to efficiently fetch more than one information about the process + at the same time, make sure to use either :meth:`oneshot` context manager + or :meth:`as_dict` utility method. + + .. note:: + + the way this class is bound to a process is via its **PID**. + That means that if the process terminates and the OS reuses its PID you may + inadvertently end up querying another process. To prevent this problem + you can use :meth:`is_running()` first. + The only methods which preemptively check whether PID has been reused + (via PID + creation time) are: + :meth:`nice` (set), + :meth:`ionice` (set), + :meth:`cpu_affinity` (set), + :meth:`rlimit` (set), + :meth:`children`, + :meth:`ppid`, + :meth:`parent`, + :meth:`parents`, + :meth:`suspend` + :meth:`resume`, + :meth:`send_signal`, + :meth:`terminate` and + :meth:`kill`. +``` + +---------------------------------------- + +TITLE: Linux Process.memory_full_info() Performance Improvement +DESCRIPTION: Significantly improves the performance of Process.memory_full_info() on Linux by reading from '/proc/pid/smaps_rollup' instead of '/proc/pids/smaps', resulting in a 5x speed increase. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_60 + +LANGUAGE: python +CODE: +``` +# Example of retrieving detailed memory info on Linux +# import psutil +# try: +# p = psutil.Process(pid) +# mem_info = p.memory_full_info() +# print(f"USS: {mem_info.uss}, PSS: {mem_info.pss}, Swap: {mem_info.swap}") +# except psutil.NoSuchProcess: +# print(f"Process with PID {pid} not found.") +# except Exception as e: +# print(f"Error retrieving memory info: {e}") +``` + +---------------------------------------- + +TITLE: cpu_percent() and cpu_times_percent() Calculation Fix (Linux) +DESCRIPTION: Corrects the calculation for cpu_percent() and cpu_times_percent() on Linux, which were previously inaccurate. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_268 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Linux]: cpu_percent() and cpu_times_percent() was calculated incorrectly. +# This ensures accurate CPU usage and time statistics on Linux. +``` + +---------------------------------------- + +TITLE: Process Num Threads/Threads Exception (Windows) +DESCRIPTION: Addresses an issue on Windows where `Process.num_threads()` and `Process.threads()` could raise `NoSuchProcess` even if the process still exists. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_541 + +LANGUAGE: python +CODE: +``` +p.num_threads() +p.threads() +``` + +---------------------------------------- + +TITLE: API Change: STATUS_* and CONN_* Constants +DESCRIPTION: The `STATUS_*` and `CONN_*` constants, previously used for process status and network connection status, have been converted into plain Python strings. This simplifies their usage and removes potential issues with JSON serialization. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_443 + +LANGUAGE: python +CODE: +``` +import psutil + +# Example: Checking process status +# if p.status() == psutil.STATUS_RUNNING: +# print("Process is running") + +# Example: Checking connection status +# for conn in psutil.net_connections(): +# if conn.status == psutil.CONN_ESTABLISHED: +# print("Established connection found") +``` + +---------------------------------------- + +TITLE: cpu_count() Logical vs. Physical Cores on Linux +DESCRIPTION: Corrects an issue on Linux where cpu_count() with logical=False returned the number of sockets instead of cores. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_380 + +LANGUAGE: python +CODE: +``` +# Original issue: cpu_count() with logical=False return the number of sockets instead of cores on Linux. +# Fix implemented in psutil version 2.1.0 +``` + +---------------------------------------- + +TITLE: Process.exe() WindowsError Handling on Windows +DESCRIPTION: Fixes an issue on Windows where Process.exe() could raise an unhandled WindowsError exception for PIDs 0 and 4. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_379 + +LANGUAGE: python +CODE: +``` +# Original issue: Process.exe() may raise unhandled WindowsError exception for PIDs 0 and 4 on Windows. +# Fix implemented in psutil version 2.1.2 +``` + +---------------------------------------- + +TITLE: Process.exe(), Process.cmdline(), Process.environ() Windows Error +DESCRIPTION: Addresses a critical bug on Windows where Process.exe(), Process.cmdline(), and Process.environ() may raise "[WinError 998] Invalid access to memory location" on Python 3.9 / VS 2019. This fix resolves memory access issues. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_88 + +LANGUAGE: APIDOC +CODE: +``` +Process.exe(), Process.cmdline(), Process.environ() + - May raise "[WinError 998] Invalid access to memory location" on Python 3.9 / VS 2019. + - Critical bug fix. +``` + +---------------------------------------- + +TITLE: Windows disk_partitions() Mountpoint Limitation Fix +DESCRIPTION: Fixes an issue on Windows where disk_partitions() only returned mountpoints on drives where it first found one. This ensures all available mountpoints are listed. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_73 + +LANGUAGE: python +CODE: +``` +# Example of retrieving disk partitions on Windows +# import psutil +# for partition in psutil.disk_partitions(): +# print(f"Device: {partition.device}, Mountpoint: {partition.mountpoint}, Fstype: {partition.fstype}") +``` + +---------------------------------------- + +TITLE: Process Memory Percentage +DESCRIPTION: Calculates the percentage of total physical system memory utilized by a process. The `memtype` parameter allows specifying which memory metric (e.g., 'rss', 'uss') to use for the comparison. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_72 + +LANGUAGE: python +CODE: +``` +import psutil +p = psutil.Process() +# Calculate memory percentage based on RSS (default) +mem_percent_rss = p.memory_percent() +# Calculate memory percentage based on USS +mem_percent_uss = p.memory_percent(memtype='uss') +``` + +---------------------------------------- + +TITLE: Common psutil Exceptions +DESCRIPTION: Defines exceptions that can be raised by psutil functions when certain conditions occur, such as insufficient permissions or a non-existent process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_561 + +LANGUAGE: APIDOC +CODE: +``` +AccessDenied + Raised when trying to access information about a process without sufficient privileges. + +NoSuchProcess + Raised when a process with a specified PID does not exist. + +TimeoutExpired + Raised when a timeout expires while waiting for a process operation. + +ZombieProcess + Raised when trying to access information about a zombie process. + +``` + +---------------------------------------- + +TITLE: Process.environ() support on AIX +DESCRIPTION: Adds support for retrieving the environment variables of a process on AIX using Process.environ(). This feature was previously unavailable on this platform. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_107 + +LANGUAGE: python +CODE: +``` +p.environ() +# Returns a dictionary of environment variables for the process. +``` + +---------------------------------------- + +TITLE: Process.cpu_affinity() Iterable Support +DESCRIPTION: Process.cpu_affinity() now accepts any iterable (set, tuple, etc.), not just lists. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_362 + +LANGUAGE: python +CODE: +``` +import psutil + +try: + p = psutil.Process() + # Example with a set + cpu_set = {0, 1} + p.cpu_affinity(cpu_set) + print(f"CPU affinity set to: {p.cpu_affinity()}") + + # Example with a tuple + cpu_tuple = (2, 3) + p.cpu_affinity(cpu_tuple) + print(f"CPU affinity set to: {p.cpu_affinity()}") + +except psutil.AccessDenied: + print("Access denied to process information.") +except ValueError as e: + print(f"ValueError: {e}. Ensure CPU cores are valid.") +``` + +---------------------------------------- + +TITLE: FreeBSD pids() ENOMEM Error Fix +DESCRIPTION: Corrects a critical issue on FreeBSD where pids() could fail with an ENOMEM error. The fix involves dynamically increasing the malloc() buffer size to accommodate larger allocations. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_52 + +LANGUAGE: python +CODE: +``` +# Conceptual example for retrieving process IDs on FreeBSD +# import psutil +# try: +# pids = psutil.pids() +# print(f"Number of processes: {len(pids)}") +# except Exception as e: +# print(f"Error retrieving PIDs: {e}") +``` + +---------------------------------------- + +TITLE: Process.open_files() Hang Fix on Windows +DESCRIPTION: Resolves a problem where Process.open_files() would hang on Windows systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_370 + +LANGUAGE: python +CODE: +``` +# Original issue: Process.open_files() no longer hangs on Windows. +# Fix implemented in psutil version 2.1.2 +``` + +---------------------------------------- + +TITLE: Process Executable Name +DESCRIPTION: Adds retrieval of the per-process executable name. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_521 + +LANGUAGE: python +CODE: +``` +p.exe() +``` + +---------------------------------------- + +TITLE: Process.parent() Exception Handling +DESCRIPTION: Addresses an issue where Process.parent() might swallow NoSuchProcess exceptions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_377 + +LANGUAGE: python +CODE: +``` +# Original issue: Process.parent() may swallow NoSuchProcess_ exceptions. +# Fix implemented in psutil version 2.1.0 +``` + +---------------------------------------- + +TITLE: Process.connections() ValueError Fix on Linux +DESCRIPTION: Fixes a 'ValueError: ambiguous inode with multiple PIDs references' for Process.connections() on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_396 + +LANGUAGE: python +CODE: +``` +# Original issue: fix "ValueError: ambiguous inode with multiple PIDs references" for Process.connections() on Linux. +# Fix implemented in psutil version 2.2.1 +``` + +---------------------------------------- + +TITLE: sensors_temperatures() Completeness Fix (Linux) +DESCRIPTION: Ensures that sensors_temperatures() on Linux displays all available temperature readings. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_235 + +LANGUAGE: python +CODE: +``` +# Original issue: [Linux]: sensors_temperatures() may not show all temperatures. +# This fix ensures comprehensive temperature reporting. +``` + +---------------------------------------- + +TITLE: cpu_percent() ZeroDivisionError Fix +DESCRIPTION: Addresses a critical bug where cpu_percent() could raise a ZeroDivisionError. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_243 + +LANGUAGE: python +CODE: +``` +# Bug fix: [critical]: cpu_percent() may raise ZeroDivisionError. +# This fix prevents division by zero errors during CPU usage calculation. +``` + +---------------------------------------- + +TITLE: psutil 5.4.3 Enhancements and Bug Fixes +DESCRIPTION: Details enhancements and bug fixes for psutil version 5.4.3. Includes improvements to disk_partitions() on Windows and a fix for pids() on macOS. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_212 + +LANGUAGE: python +CODE: +``` +5.4.3 + +*2018-01-01* + +**Enhancements** + +- disk_partitions() on Windows return mount points. + +**Bug fixes** + +- pids() may return False on macOS. +``` + +---------------------------------------- + +TITLE: Windows Virtual Secure Mode Process Handling +DESCRIPTION: Fixes an issue on Windows where Process.exe() would return '[Error 0] The operation completed successfully' when the Python process was running in 'Virtual Secure Mode'. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_172 + +LANGUAGE: python +CODE: +``` +# [Windows]: Process.exe() returns "[Error 0] The operation completed successfully" when Python process runs in "Virtual Secure Mode". +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes - Process.open_files() on Windows +DESCRIPTION: Addresses an issue where Process.open_files() could hang on Windows systems. This fix improves stability and prevents resource locking. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_422 + +LANGUAGE: python +CODE: +``` +# Fix for psutil.Process.open_files() hanging on Windows +# Original issue: https://github.com/giampaolo/psutil/issues/340 +``` + +---------------------------------------- + +TITLE: String Encoding (OS fs encoding) +DESCRIPTION: Ensures all strings returned by psutil are encoded using the operating system's filesystem encoding for better compatibility. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_225 + +LANGUAGE: python +CODE: +``` +# Original issue: all strings are encoded by using OS fs encoding. +# This change improves handling of filenames and paths across different systems. +``` + +---------------------------------------- + +TITLE: disk_partitions() Empty List Fix on Linux +DESCRIPTION: Resolves an issue on Linux where disk_partitions() might return an empty list. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_394 + +LANGUAGE: python +CODE: +``` +# Original issue: disk_partitions() return an empty list on Linux. +# Fix implemented in psutil version 2.1.0 +``` + +---------------------------------------- + +TITLE: Linux net_if_stats() 100GbE Interface Speed Correction +DESCRIPTION: Addresses an issue on Linux where net_if_stats() reported incorrect interface speeds for 100GbE network cards. This ensures accurate network performance metrics. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_53 + +LANGUAGE: python +CODE: +``` +# Example of retrieving network interface statistics on Linux +# import psutil +# try: +# net_stats = psutil.net_if_stats() +# for interface, stats in net_stats.items(): +# print(f"Interface: {interface}, Speed: {stats.speed} Mbps") +# except Exception as e: +# print(f"Error retrieving network stats: {e}") +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes and Enhancements by Platform +DESCRIPTION: Details specific bug fixes and enhancements for the psutil library across different operating systems like SunOS, Windows, Linux, and macOS. This includes issues with process command lines, CPU counts, time reporting, memory information, and sensor data. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_211 + +LANGUAGE: python +CODE: +``` +Project: /giampaolo/psutil + +- [SunOS]: Process.cmdline() could be truncated at the 15th character when reading it from /proc. An extra effort is made by reading it from process address space first. +- [Windows]: cpu_count() (both logical and cores) return a wrong (smaller) number on systems using process groups (> 64 cores). +- [Windows]: cpu_times() with percpu=True return fewer CPUs on systems using process groups (> 64 cores). +- [Windows]: cpu_stats() and cpu_freq() may return incorrect results on systems using process groups (> 64 cores). +- [SunOS]: return uid/gid from /proc/pid/psinfo if there aren't enough permissions for /proc/pid/cred. +- [SunOS]: return nice value from psinfo as getpriority() doesn't support real-time processes. +- [SunOS]: fix double free() in Process.cpu_num(). +- [SunOS]: fix undefined behavior related to strict-aliasing rules and warnings. +- [Linux]: cpu_percent() steal time may remain stuck at 100% due to Linux erroneously reporting a decreased steal time between calls. +- [Windows]: fix compatibility with Python 2.6 on Windows. +- [Linux]: Process.memory_full_info() was erroneously summing "Swap:" and "SwapPss:". Same for "Pss:" and "SwapPss". Not anymore. +- [Windows]: Process.wait() may erroneously raise TimeoutExpired. +- [Linux]: sensors_battery() may return None in case battery is not listed as "BAT0" under /sys/class/power_supply. +- [Windows]: cpu_times() float loses accuracy in a long running system. +- [Linux]: sensors_temperatures() may fail with IOError "no such file". +- [FreeBSD]: swap_memory() stats were erroneously represented in KB. + +Backward compatibility: +- [Windows]: cpu_count() with logical=False on Windows XP and Vista is no longer supported and returns None. +``` + +---------------------------------------- + +TITLE: Add sensors_battery() (Linux, Windows) +DESCRIPTION: Introduces the sensors_battery() function, supporting Linux and Windows, to retrieve battery status information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_255 + +LANGUAGE: python +CODE: +``` +# Enhancement: added sensors_battery() (Linux, Windows, only). +# This function provides detailed battery status including percentage and power state. +``` + +---------------------------------------- + +TITLE: virtual_memory() Memory Handling +DESCRIPTION: On Linux, virtual_memory() provides more accurate results on systems with a large amount of physical memory. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_347 + +LANGUAGE: python +CODE: +``` +psutil.virtual_memory() +``` + +---------------------------------------- + +TITLE: Process Path Alias +DESCRIPTION: The `psutil.Process.path` property is now deprecated and acts as an alias for `psutil.Process.exe`. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_535 + +LANGUAGE: APIDOC +CODE: +``` +Process: + path: Deprecated alias for exe. +``` + +---------------------------------------- + +TITLE: SunOS Swap Output Error Fix +DESCRIPTION: Corrects an error in swap output on SunOS due to an incorrect range calculation, ensuring accurate swap space reporting. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_74 + +LANGUAGE: python +CODE: +``` +# Example of retrieving swap memory statistics on SunOS +# import psutil +# try: +# swap = psutil.swap_memory() +# print(f"Swap Total: {swap.total}, Swap Used: {swap.used}") +# except Exception as e: +# print(f"Error retrieving swap info: {e}") +``` + +---------------------------------------- + +TITLE: psutil.get_pid_list() Limit on Windows +DESCRIPTION: Fixes an issue on Windows where psutil.get_pid_list() was limited to showing only 1024 processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_465 + +LANGUAGE: python +CODE: +``` +# Fix for the 1024 process limit in psutil.get_pid_list() on Windows. +``` + +---------------------------------------- + +TITLE: macOS Process File Descriptor Buffer Size Increase +DESCRIPTION: Addresses potential AccessDenied exceptions in Process.open_files() and Process.connections() on macOS by dynamically increasing the internal buffer size for proc_pidinfo syscalls. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_76 + +LANGUAGE: python +CODE: +``` +# Example of handling potential AccessDenied when accessing process file descriptors +# import psutil +# try: +# p = psutil.Process(pid) +# open_files = p.open_files() +# connections = p.connections() +# print(f"Open files count: {len(open_files)}") +# print(f"Connections count: {len(connections)}") +# except psutil.AccessDenied: +# print("Access denied, possibly due to buffer size issues (now fixed).") +# except psutil.NoSuchProcess: +# print("Process not found.") +``` + +---------------------------------------- + +TITLE: Filter Processes by Status (Running) +DESCRIPTION: This snippet shows how to filter processes that are currently in a running state. It accesses the 'status' field of each process's information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_97 + +LANGUAGE: python +CODE: +``` +import psutil +from pprint import pprint as pp + +pp([(p.pid, p.info) for p in psutil.process_iter(['name', 'status']) if p.info['status'] == psutil.STATUS_RUNNING]) +``` + +---------------------------------------- + +TITLE: ZombieProcess Exception Handling +DESCRIPTION: Introduced a new ZombieProcess exception class for correct handling of zombie processes on POSIX systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_364 + +LANGUAGE: python +CODE: +``` +import psutil + +try: + # Attempt to interact with a process that might be a zombie + # This is a conceptual example as creating a zombie process is platform-specific + # For demonstration, we'll simulate catching the exception + pass # Replace with actual process interaction if needed +except psutil.ZombieProcess as e: + print(f"Encountered a zombie process: {e}") +except Exception as e: + print(f"An unexpected error occurred: {e}") +``` + +---------------------------------------- + +TITLE: Add sensors_temperatures() (Linux) +DESCRIPTION: Introduces the sensors_temperatures() function, specifically for Linux systems, to retrieve temperature readings. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_253 + +LANGUAGE: python +CODE: +``` +# Enhancement: added sensors_temperatures() (Linux only). +# This function allows monitoring of system temperatures on Linux. +``` + +---------------------------------------- + +TITLE: Network I/O Counters +DESCRIPTION: Retrieves system-wide network I/O statistics. Can return per-network interface statistics if pernic is True. Handles potential integer overflows with the nowrap argument. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_16 + +LANGUAGE: python +CODE: +``` +import psutil + +# Get system-wide network I/O counters +print(psutil.net_io_counters()) + +# Get per-network interface I/O counters +print(psutil.net_io_counters(pernic=True)) +``` + +---------------------------------------- + +TITLE: MUSL C Library Compilation Support (Linux) +DESCRIPTION: Enables psutil to compile on Linux systems using the MUSL C library. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_239 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Linux]: can now compile on Linux by using MUSL C library. +# This improves compatibility with alternative C libraries on Linux. +``` + +---------------------------------------- + +TITLE: HISTORY.rst Hyperlink Rewriting +DESCRIPTION: Rewrites the HISTORY.rst file to use hyperlinks that point to the psutil API documentation, improving navigation and cross-referencing within the documentation. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_70 + +LANGUAGE: markdown +CODE: +``` +## Version 5.9.0 + +**Enhancements** + +- [1851] [Linux]: `cpu_freq()` is slow on systems with many CPUs. Read current frequency values for all CPUs from `/proc/cpuinfo` instead of opening many files in `/sys` fs. (patch by marxin) +- [1992] `NoSuchProcess` message now specifies if the PID has been reused. +- [1992] error classes (`NoSuchProcess`, `AccessDenied`, etc.) now have a better formatted and separated `__repr__` and `__str__` implementations. +- [1996] [BSD]: add support for MidnightBSD. (patch by Saeed Rasooli) +- [1999] [Linux]: `disk_partitions()`: convert `/dev/root` device (an alias used on some Linux distros) to real root device path. +- [2005] `PSUTIL_DEBUG` mode now prints file name and line number of the debug messages coming from C extension modules. +- [2042] rewrite HISTORY.rst to use hyperlinks pointing to psutil API doc. +``` + +---------------------------------------- + +TITLE: Windows cpu_times() Enhancements +DESCRIPTION: On Windows, cpu_times() and cpu_times_percent() now return two new fields: 'interrupt' and 'dpc'. These fields provide specific CPU time metrics relevant to the Windows operating system. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_323 + +LANGUAGE: python +CODE: +``` +process.cpu_times() +``` + +LANGUAGE: python +CODE: +``` +process.cpu_times_percent() +``` + +---------------------------------------- + +TITLE: Process.status() Zombie Process Handling (macOS) +DESCRIPTION: Corrects Process.status() on macOS to accurately report the status of zombie processes, preventing them from being erroneously marked as 'running'. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_297 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +try: + # Assuming 'pid' refers to a zombie process PID + p = Process(pid) + status = p.status() + print(f"Process status: {status}") + # The status should not be 'running' for a zombie process. +except Exception as e: + print(f"An error occurred: {e}") +``` + +---------------------------------------- + +TITLE: Process Properties Converted to Methods +DESCRIPTION: Most properties of the `Process` class have been converted into methods, with the exception of `pid`. This change standardizes access to process information, requiring method calls instead of direct attribute access. For instance, `p.name` is now `p.name()`. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_437 + +LANGUAGE: python +CODE: +``` +Assuming p = psutil.Process(): + +p.name() # Formerly p.name +p.parent() # Formerly p.parent +p.ppid() # Formerly p.ppid +p.exe() # Formerly p.exe +p.cmdline() # Formerly p.cmdline +p.status() # Formerly p.status +p.uids() # Formerly p.uids +p.gids() # Formerly p.gids +p.username() # Formerly p.username +p.create_time() # Formerly p.create_time +``` + +---------------------------------------- + +TITLE: Windows users() Multiple Calls Crash Fix +DESCRIPTION: Fixes a 'Fatal Python error: deallocating None' crash that occurred when calling the users() function multiple times on Windows. This ensures stable user session retrieval. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_84 + +LANGUAGE: python +CODE: +``` +# Example of retrieving logged-in users on Windows +# import psutil +# try: +# # Call users() multiple times to test the fix +# for _ in range(5): +# users = psutil.users() +# print(f"Logged-in users: {len(users)}") +# except Exception as e: +# print(f"Error retrieving users: {e}") +``` + +---------------------------------------- + +TITLE: Process.ppid() Speedup (Linux) +DESCRIPTION: Enhances the performance of Process.ppid() by 20% on Linux through optimized /proc parsing. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_291 + +LANGUAGE: python +CODE: +``` +from psutil import Process +import time + +p = Process() + +start_time = time.time() +ppid = p.ppid() +print(f"Parent PID: {ppid}, Time taken: {time.time() - start_time:.6f}s") +``` + +---------------------------------------- + +TITLE: Iterate Over Processes Safely +DESCRIPTION: Provides an iterator that yields `Process` instances for all running processes. It's safer than `pids()` for iteration and avoids race conditions. It supports fetching specific process attributes and has a cache that can be cleared. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_27 + +LANGUAGE: python +CODE: +``` +import psutil + +# Iterate and print PID, name, and username for each process +for proc in psutil.process_iter(['pid', 'name', 'username']): + print(proc.info) + +# Create a dictionary of {pid: info} +procs = {p.pid: p.info for p in psutil.process_iter(['name', 'username'])} + +# Clear the internal cache +psutil.process_iter.cache_clear() +``` + +---------------------------------------- + +TITLE: CPU Count: Logical vs. Physical Cores +DESCRIPTION: Enhances cpu_count() to provide information about both logical CPUs and physical cores. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_409 + +LANGUAGE: python +CODE: +``` +# Enhancement: number of logical CPUs and physical cores (cpu_count()). +# Implemented in psutil version 2.0.0 +``` + +---------------------------------------- + +TITLE: API Changes in psutil 0.7.0 +DESCRIPTION: Details API modifications in psutil version 0.7.0, including deprecation of the psutil.error module and changes to process attribute caching. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_448 + +LANGUAGE: APIDOC +CODE: +``` +Process.cmdline(): + - property is no longer cached after first access. +Process.ppid(): + - property is no longer cached after first access. +[Linux] Process methods: + - methods not working due to poor /proc implementation will raise NotImplementedError instead of RuntimeError. +psutil.error module: + - deprecated and scheduled for removal. +``` + +---------------------------------------- + +TITLE: Process.send_signal() Enhancements +DESCRIPTION: Added support for CTRL_C_EVENT and CTRL_BREAK_EVENT signals on Windows for use with Process.send_signal(). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_358 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +try: + p = Process(pid) + p.send_signal(signal.CTRL_C_EVENT) # Example for CTRL_C_EVENT +except Exception as e: + print(f"Error sending signal: {e}") +``` + +---------------------------------------- + +TITLE: psutil.Popen Class +DESCRIPTION: Introduces a `psutil.Popen` class that combines `subprocess.Popen` and `psutil.Process` for a unified interface. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_501 + +LANGUAGE: python +CODE: +``` +psutil.Popen(cmd, ... +``` + +---------------------------------------- + +TITLE: Process Properties Caching +DESCRIPTION: Properties like ppid(), name(), exe(), cmdline(), and create_time() are now cached after access. This prevents NoSuchProcess exceptions if the process terminates between accesses. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_469 + +LANGUAGE: python +CODE: +``` +# Properties are now cached: +# ppid, name, exe, cmdline, create_time +``` + +---------------------------------------- + +TITLE: Process.as_dict() Deprecation Handling +DESCRIPTION: Ensures Process.as_dict() does not call the deprecated Process.memory_info_ex() method. It also handles erroneous attribute names passed to as_dict() by ignoring them. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_277 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +p = Process() +# This call should now work correctly without calling deprecated methods +# and ignoring invalid attribute names. +data = p.as_dict(attrs=['pid', 'name', 'invalid_attr']) +print(data) +``` + +---------------------------------------- + +TITLE: Process.cpu_percent() Calculation Fix (Windows) +DESCRIPTION: Corrects the calculation of Process.cpu_percent() on Windows, which was previously showing higher usage than actual. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_259 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Windows]: Process.cpu_percent() was calculated incorrectly and showed higher number than real usage. +# This ensures accurate CPU usage reporting for processes on Windows. +``` + +---------------------------------------- + +TITLE: Exception Attributes +DESCRIPTION: Enhances `NoSuchProcess` and `AccessDenied` exception classes to include `pid`, `name`, and `msg` attributes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_516 + +LANGUAGE: APIDOC +CODE: +``` +Exceptions: + NoSuchProcess(pid, name, msg): + Attributes: pid, name, msg + AccessDenied(pid, name, msg): + Attributes: pid, name, msg +``` + +---------------------------------------- + +TITLE: Process.io_counters() NotImplementedError for Old Linux +DESCRIPTION: Process.io_counters() now raises NotImplementedError on old Linux versions where I/O counters are not available, instead of erroneously raising NoSuchProcess. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_467 + +LANGUAGE: python +CODE: +``` +try: + process.io_counters() +except psutil.NotImplementedError: + print('I/O counters not available for this process.') +``` + +---------------------------------------- + +TITLE: Process.memory_maps() on Windows (Address Truncation) +DESCRIPTION: Fixes an issue on Windows where Process.memory_maps() would truncate addresses exceeding 32 bits. This ensures accurate memory address reporting. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_278 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +p = Process() +memory_maps = p.memory_maps() +# Addresses should now be correctly represented, even above 32 bits +``` + +---------------------------------------- + +TITLE: Process.cpu_affinity() Error Handling on Linux +DESCRIPTION: Fixes a critical issue on Linux where Process.cpu_affinity() with [-1] would raise a SystemError. It now correctly raises a ValueError for invalid arguments. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_285 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +try: + p = Process() + p.cpu_affinity([-1]) +except ValueError as e: + print(f"Successfully caught ValueError: {e}") +except Exception as e: + print(f"Caught unexpected exception: {e}") +``` + +---------------------------------------- + +TITLE: Per-Process Children +DESCRIPTION: Adds functionality to retrieve a process's children. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_517 + +LANGUAGE: python +CODE: +``` +p.children() +``` + +---------------------------------------- + +TITLE: macOS Process.environ() Garbage Data Fix +DESCRIPTION: Addresses an out-of-bounds read issue in Process.environ() on macOS, potentially causing garbage data. This fix involves adjustments around sysctl_procargs. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_46 + +LANGUAGE: python +CODE: +``` +# Example demonstrating the fix for Process.environ() on macOS +# (Actual code not provided, this is a conceptual representation) +# from psutil import Process +# try: +# env = Process(pid).environ() +# # Process env data +# except Exception as e: +# print(f"Error accessing environment: {e}") +``` + +---------------------------------------- + +TITLE: Hardware Fan Speeds +DESCRIPTION: Retrieves the speed of hardware fans in RPM. Returns an empty dictionary if sensors are not supported. Available on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_22 + +LANGUAGE: python +CODE: +``` +import psutil + +fan_speeds = psutil.sensors_fans() +print(f"Fan Speeds: {fan_speeds}") +``` + +---------------------------------------- + +TITLE: Process Handle Race Condition (Linux Fix) +DESCRIPTION: Fixes a race condition on Linux that could cause an `IOError` if a process disappears between `open()` and `read()` calls. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_505 + +LANGUAGE: python +CODE: +``` +open(path).read() +``` + +---------------------------------------- + +TITLE: sensors_temperatures() ENODEV Error Handling (Linux) +DESCRIPTION: Handles cases on Linux where sensors_temperatures() might raise an ENODEV error, likely due to missing sensor hardware. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_222 + +LANGUAGE: python +CODE: +``` +# Original issue: sensors_temperatures() may raise ENODEV. +# Fix involves adding error handling for ENODEV to gracefully manage missing sensor devices. +``` + +---------------------------------------- + +TITLE: Process PID 0 Path/CWD Consistency (Linux Fix) +DESCRIPTION: Fixes inconsistent data returned by `Process.exe()` and `Process.cwd()` for PID 0 on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_508 + +LANGUAGE: python +CODE: +``` +p.exe() +p.cwd() +``` + +---------------------------------------- + +TITLE: Process.cpu_times() iowait counter +DESCRIPTION: Adds the 'iowait' counter to Process.cpu_times() on Linux, representing time spent waiting for I/O operations. This enhancement improves the granularity of CPU time tracking for processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_100 + +LANGUAGE: python +CODE: +``` +p.cpu_times() +# Example output might include: +# pcputimes(user=10.5, system=2.1, children_user=0.0, children_system=0.0, iowait=0.5) +``` + +---------------------------------------- + +TITLE: Process.cpu_affinity() on Linux +DESCRIPTION: Fixes a critical issue on Linux where Process.cpu_affinity() with an argument of [-1] would raise a SystemError. The fix ensures a ValueError is raised instead, providing clearer error handling. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_272 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +try: + p = Process() + # Attempting to set affinity with [-1] should now raise ValueError + p.cpu_affinity([-1]) +except ValueError as e: + print(f"Caught expected error: {e}") +except Exception as e: + print(f"Caught unexpected error: {e}") +``` + +---------------------------------------- + +TITLE: Compilation fix on OpenBSD +DESCRIPTION: Resolves a critical C syntax error that caused compilation to fail on OpenBSD. This ensures psutil can be successfully compiled on OpenBSD systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_151 + +LANGUAGE: python +CODE: +``` +# Internal C code adjustment for OpenBSD compatibility. +``` + +---------------------------------------- + +TITLE: Process.as_dict() ValueError Handling +DESCRIPTION: Fixes Process.as_dict() to raise a ValueError if an invalid attribute name is provided, improving input validation. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_304 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +try: + p = Process() + p.as_dict(attrs=['invalid_attribute']) +except ValueError as e: + print(f"Caught expected ValueError: {e}") +except Exception as e: + print(f"Caught unexpected exception: {e}") +``` + +---------------------------------------- + +TITLE: Process.username() and users() Decoding Fix (Windows) +DESCRIPTION: Fixes issues with badly decoded characters returned by Process.username() and users() on Windows with Python 3. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_248 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Windows]: Process.username() and users() may return badly decoded character on Python 3. +# This ensures correct decoding of user information. +``` + +---------------------------------------- + +TITLE: OSX Alias for MACOS +DESCRIPTION: An alias for the MACOS platform constant. It is deprecated since version 5.4.7 and users are advised to use psutil.MACOS instead. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_92 + +LANGUAGE: python +CODE: +``` +import psutil + +# Deprecated usage: +# if psutil.OSX: +# print("Running on macOS (using deprecated OSX alias)") + +# Recommended usage: +if psutil.MACOS: + print("Running on macOS") + +``` + +---------------------------------------- + +TITLE: cpu_percent() Negative Integer Handling +DESCRIPTION: Ensures that passing a negative integer to cpu_percent() functions raises a ValueError, improving input validation. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_311 + +LANGUAGE: python +CODE: +``` +from psutil import cpu_percent + +try: + cpu_percent(-1) +except ValueError as e: + print(f"Caught expected ValueError: {e}") +except Exception as e: + print(f"Caught unexpected exception: {e}") +``` + +---------------------------------------- + +TITLE: Exception Namespace Change +DESCRIPTION: The deprecated `psutil.error` module has been removed. Exception classes are now directly available under the `psutil` namespace for cleaner access. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_439 + +LANGUAGE: python +CODE: +``` +# Old way (deprecated and removed): +# from psutil.error import AccessDenied + +# New way: +from psutil import AccessDenied +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes - Process.name() and Process.cmdline() Encoding +DESCRIPTION: Corrects encoding errors encountered when retrieving process names (Process.name()) and command lines (Process.cmdline()) on Linux systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_432 + +LANGUAGE: python +CODE: +``` +# Fix for encoding errors in psutil.Process.name() and psutil.Process.cmdline() on Linux +# Original issue: https://github.com/giampaolo/psutil/issues/476 +``` + +---------------------------------------- + +TITLE: Compilation fix on OpenBSD +DESCRIPTION: Resolves a critical C syntax error that caused compilation to fail on OpenBSD. This ensures psutil can be successfully compiled on OpenBSD systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_122 + +LANGUAGE: python +CODE: +``` +# Internal C code adjustment for OpenBSD compatibility. +``` + +---------------------------------------- + +TITLE: cpu_count() logical core determination on Linux +DESCRIPTION: Enhances cpu_count(logical=False) on Linux by adding a secondary method to determine the number of CPU cores. It now reads from '/sys/devices/system/cpu/cpu[0-9]/topology/core_id' when '/proc/cpuinfo' does not provide sufficient information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_106 + +LANGUAGE: python +CODE: +``` +psutil.cpu_count(logical=False) +# Provides a more accurate physical core count on systems with complex CPU topologies. +``` + +---------------------------------------- + +TITLE: Monotonic Process Creation Time on Linux +DESCRIPTION: Bug fix for psutil version 7.0.1: Utilizes a monotonic creation time for processes on Linux to prevent issues with system clock updates affecting Process.is_running(). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_6 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to internal implementation. +``` + +---------------------------------------- + +TITLE: Access Denied Exception +DESCRIPTION: Introduces the `AccessDenied` exception, which is raised when the operating system denies access to process information due to insufficient privileges. This is often raised from `OSError` or `WindowsError`. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_552 + +LANGUAGE: python +CODE: +``` +AccessDenied +``` + +---------------------------------------- + +TITLE: net_if_addrs() Broadcast Address on Windows +DESCRIPTION: Enhancement for psutil version 7.0.0: net_if_addrs() on Windows now returns the broadcast address instead of None. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_17 + +LANGUAGE: python +CODE: +``` +import psutil + +# Example usage +# for interface, addrs in psutil.net_if_addrs().items(): +# for addr in addrs: +# if addr.family == psutil.AF_LINK: +# print(f"Interface: {interface}, Broadcast: {addr.broadcast}") +``` + +---------------------------------------- + +TITLE: Process.memory_maps() Segfault Fix on FreeBSD +DESCRIPTION: Resolves a critical segfault occurring in Process.memory_maps() on FreeBSD systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_367 + +LANGUAGE: python +CODE: +``` +# Original issue: Process.memory_maps() segfaults on FreeBSD. +# Fix implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes - Process.exe() Null Bytes on Linux +DESCRIPTION: Addresses improper null byte handling in Process.exe() on Linux, ensuring correct retrieval of executable paths. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_427 + +LANGUAGE: python +CODE: +``` +# Fix for improper null bytes handling in psutil.Process.exe() on Linux +# Original issue: https://github.com/giampaolo/psutil/issues/466 +``` + +---------------------------------------- + +TITLE: Process.memory_full_info() AccessDenied on Windows +DESCRIPTION: Fixes a critical bug on Windows where Process.memory_full_info() raised AccessDenied even for the current user and os.getpid(). This ensures memory information is accessible for the current process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_140 + +LANGUAGE: python +CODE: +``` +p.memory_full_info() +# Should no longer raise AccessDenied for the current user. +``` + +---------------------------------------- + +TITLE: Process.open_files() Crash Fix (Windows) +DESCRIPTION: Fixes a crash in Process.open_files() on Windows that occurred when the worker thread for NtQueryObject timed out. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_240 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Windows]: Fix a crash in Process.open_files() when the worker thread for NtQueryObject times out. +# This ensures the stability of file enumeration for processes. +``` + +---------------------------------------- + +TITLE: System Memory and Network I/O Enhancements +DESCRIPTION: This snippet highlights improvements to system memory and network I/O monitoring functions in psutil. It includes the introduction of new functions for detailed memory representation and expanded fields in network I/O statistics to capture error and dropped packets. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_451 + +LANGUAGE: python +CODE: +``` +virtual_memory() # New function for detailed system memory representation +swap_memory() # New function for swap memory representation +net_io_counters() # Includes errin, errout, dropin, and dropout fields +``` + +---------------------------------------- + +TITLE: Process.cpu_times() Type Consolidation (Windows) +DESCRIPTION: Corrects type inconsistencies in Process.cpu_times() on Windows, ensuring fields #3 and #4 are floats instead of integers. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_223 + +LANGUAGE: python +CODE: +``` +# Original issue: Windows / Process.cpu_times(): fields #3 and #4 were int instead of float. +# Fix ensures these fields return float values for consistency. +``` + +---------------------------------------- + +TITLE: Process.children() Accuracy Fix +DESCRIPTION: Corrects an issue where Process.children() could sometimes return non-children processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_468 + +LANGUAGE: python +CODE: +``` +# Fix for Process.children() returning incorrect processes. +``` + +---------------------------------------- + +TITLE: Android Compilation Fix for ethtool_cmd_speed +DESCRIPTION: Resolves a compilation issue on Android where the psutil library failed due to an undefined symbol 'ethtool_cmd_speed'. This fix is critical for Linux environments targeting Android. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_47 + +LANGUAGE: python +CODE: +``` +# Conceptual representation of the fix for Android compilation +# Ensure necessary headers or definitions for ethtool_cmd_speed are available +# during compilation on Android. +``` + +---------------------------------------- + +TITLE: psutil API Renames - Module Level Constants +DESCRIPTION: This section details the replacement of psutil module-level constants with functions for better consistency. Accessing old names will raise a DeprecationWarning. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_419 + +LANGUAGE: APIDOC +CODE: +``` +psutil.* module level constants have being replaced by functions: + +Old name: psutil.NUM_CPUS +Replacement: psutil.cpu_count() + +Old name: psutil.BOOT_TIME +Replacement: psutil.boot_time() + +Old name: psutil.TOTAL_PHYMEM +Replacement: virtual_memory.total +``` + +---------------------------------------- + +TITLE: Handling of Offline CPUs in cpu_freq() +DESCRIPTION: Previously, offline CPUs could raise a NotImplementedError when calling cpu_freq(). This fix ensures that cpu_freq() handles offline CPUs gracefully, likely by returning default or indicative values. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_36 + +LANGUAGE: python +CODE: +``` +# Example of calling cpu_freq() +try: + freq = psutil.cpu_freq() + print(f"Current CPU frequency: {freq.current} MHz") +except NotImplementedError: + print("CPU frequency information not available.") +``` + +---------------------------------------- + +TITLE: Linux CPU Frequency Parsing +DESCRIPTION: Enhances cpu_freq() on Linux by adding an implementation that parses /proc/cpuinfo as a fallback when the /sys/devices/system/cpu/* filesystem is unavailable. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_184 + +LANGUAGE: python +CODE: +``` +# [Linux]: cpu_freq() is now implemented by parsing /proc/cpuinfo in case /sys/devices/system/cpu/* filesystem is not available. +``` + +---------------------------------------- + +TITLE: Process.cwd() Exception Handling (Linux) +DESCRIPTION: Corrects Process.cwd() on Linux to raise ZombieProcess instead of NoSuchProcess for zombie processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_241 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Linux]: Process.cwd() may raise NoSuchProcess instead of ZombieProcess. +# This ensures the correct exception type is raised for zombie processes. +``` + +---------------------------------------- + +TITLE: Windows swap_memory() Committed Memory vs Swap Fix +DESCRIPTION: Corrects an issue on Windows where swap_memory() was showing committed memory instead of actual swap usage. This ensures accurate swap space reporting. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_80 + +LANGUAGE: python +CODE: +``` +# Example of retrieving swap memory statistics on Windows +# import psutil +# try: +# swap = psutil.swap_memory() +# print(f"Swap Total: {swap.total}, Swap Used: {swap.used}") +# except Exception as e: +# print(f"Error retrieving swap memory: {e}") +``` + +---------------------------------------- + +TITLE: Python Version Support Changes +DESCRIPTION: Details changes in Python version support, including dropping support for older versions and ensuring compatibility with newer ones. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_397 + +LANGUAGE: python +CODE: +``` +# Enhancement: drop support for Python 2.4 and 2.5. +# Implemented in psutil version 2.2.0 + +# Bug fix: Python 2.4 support was broken on Linux. +# Fix implemented in psutil version 2.1.2 +``` + +---------------------------------------- + +TITLE: Unicode Handling in psutil APIs (Python 2) +DESCRIPTION: On Python 2, APIs returning strings now return an encoded version using sys.getfilesystemencoding() codec to handle unicode issues, particularly with non-ASCII NIC names. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_360 + +LANGUAGE: python +CODE: +``` +# Example for net_if_addrs() on Python 2 +import psutil +import sys + +try: + addresses = psutil.net_if_addrs() + for interface, addrs in addresses.items(): + for addr in addrs: + if addr.family == psutil.AF_INET: + print(f"Interface: {interface}, IP Address: {addr.address}") +except UnicodeDecodeError as e: + print(f"UnicodeDecodeError: {e}. Ensure filesystem encoding is handled.") +``` + +---------------------------------------- + +TITLE: Process.memory_maps() Path Handling +DESCRIPTION: On Linux, Process.memory_maps() may now correctly handle paths that end with " (deleted)", preventing potential issues with identifying deleted memory-mapped files. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_332 + +LANGUAGE: python +CODE: +``` +process.memory_maps() +``` + +---------------------------------------- + +TITLE: Process Memory Full Information +DESCRIPTION: Retrieves detailed memory information for a process, including Resident Set Size (RSS), Virtual Memory Size (VMS), shared memory, private memory (USS), Proportional Set Size (PSS), and swap usage. USS is highlighted as a representative metric for actual memory usage. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_71 + +LANGUAGE: python +CODE: +``` +import psutil +p = psutil.Process() +p.memory_full_info() +# Example Output: +pfullmem(rss=10199040, vms=52133888, shared=3887104, text=2867200, lib=0, data=5967872, dirty=0, uss=6545408, pss=6872064, swap=0) +``` + +---------------------------------------- + +TITLE: System Cached and Buffered Memory +DESCRIPTION: Provides information on total system physical cached memory and memory buffers used by the kernel. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_514 + +LANGUAGE: python +CODE: +``` +psutil.cached_memory() +psutil.buffered_memory() +``` + +---------------------------------------- + +TITLE: Process Methods Error Masking Fix (macOS/BSD) +DESCRIPTION: Corrects how different process methods handle errors for high-privileged PIDs on macOS and BSD, preventing masking of real errors and ensuring correct exceptions (NoSuchProcess, AccessDenied) are raised. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_302 + +LANGUAGE: python +CODE: +``` +from psutil import Process, NoSuchProcess, AccessDenied + +try: + # Example: Attempting to access info for a high-privileged PID + p = Process(pid=1) + p.name() +except (NoSuchProcess, AccessDenied) as e: + print(f"Correctly caught expected exception: {e}") +except Exception as e: + print(f"Caught unexpected exception: {e}") +``` + +---------------------------------------- + +TITLE: Deprecated API Functions +DESCRIPTION: This snippet lists deprecated psutil functions and their recommended replacements. It indicates that functions like `psutil.phymem_usage()` and `psutil.virtmem_usage()` are deprecated and provides the new functions to use instead. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_454 + +LANGUAGE: python +CODE: +``` +psutil.phymem_usage() # Deprecated, use virtual_memory() +psutil.virtmem_usage() # Deprecated, use swap_memory() (or virtual_memory() on Linux) +psutil.cached_phymem() # Deprecated on Linux, use virtual_memory() +``` + +---------------------------------------- + +TITLE: FreeBSD CPU Affinity Fix +DESCRIPTION: Fixes an issue related to Process.cpu_affinity() on FreeBSD, specifically addressing potential segfaults with invalid CPU numbers. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_418 + +LANGUAGE: python +CODE: +``` +# Original issue: Process.cpu_affinity() segfaults on set in case an invalid CPU number is provided on FreeBSD. +# Fix implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: Linux cpu_freq() Performance Improvement +DESCRIPTION: Enhances the performance of cpu_freq() on Linux systems with many CPUs by reading frequency values from '/proc/cpuinfo' instead of opening multiple files in '/sys' fs. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_64 + +LANGUAGE: python +CODE: +``` +# Example of retrieving CPU frequency, optimized for multi-CPU systems +# import psutil +# freq = psutil.cpu_freq() +# if freq: +# print(f"CPU Frequency: {freq.current} MHz") +``` + +---------------------------------------- + +TITLE: net_connections() type and family fields +DESCRIPTION: Ensures that the 'type' and 'family' fields returned by net_connections() are consistently converted into enums. This improves the type safety and predictability of network connection information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_103 + +LANGUAGE: python +CODE: +``` +p.connections() +# Example of connection info: +# [sconn(fd=123, family=, type=, laddr=('127.0.0.1', 8080), raddr=('127.0.0.1', 9090))] +``` + +---------------------------------------- + +TITLE: Process.memory_full_info() AccessDenied on Windows +DESCRIPTION: Fixes a critical bug on Windows where Process.memory_full_info() raised AccessDenied even for the current user and os.getpid(). This ensures memory information is accessible for the current process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_111 + +LANGUAGE: python +CODE: +``` +p.memory_full_info() +# Should no longer raise AccessDenied for the current user. +``` + +---------------------------------------- + +TITLE: Windows TimeoutException on Wait +DESCRIPTION: Addresses an issue on Windows where `Process.wait()` could raise a `TimeoutException` when a process returned -1. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_536 + +LANGUAGE: python +CODE: +``` +p.wait() +``` + +---------------------------------------- + +TITLE: Pytest Migration +DESCRIPTION: Enhancement for psutil version 6.1.0: Migrated from unittest to pytest for testing. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_26 + +LANGUAGE: bash +CODE: +``` +pytest +``` + +---------------------------------------- + +TITLE: Process Memory Information +DESCRIPTION: Retrieves detailed memory information for a process. This method provides insights into the memory footprint of a process, including resident set size, virtual memory size, and other related metrics. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_35 + +LANGUAGE: APIDOC +CODE: +``` +memory_full_info() + Retrieves detailed memory information for a process. + Returns: A named tuple with various memory usage details. +``` + +LANGUAGE: APIDOC +CODE: +``` +memory_maps() + Returns a list of memory mappings for the process. + Returns: A list of named tuples, each representing a memory map. +``` + +---------------------------------------- + +TITLE: macOS CPU Percent Fix +DESCRIPTION: Fixes an issue on macOS where `cpu_percent()` was always returning 100%. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_532 + +LANGUAGE: python +CODE: +``` +psutil.cpu_percent() +``` + +---------------------------------------- + +TITLE: net_if_addrs() Netmask on Windows +DESCRIPTION: Enhances net_if_addrs() on Windows to also return the 'netmask' for network interfaces, providing more complete network configuration details. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_283 + +LANGUAGE: python +CODE: +``` +from psutil import net_if_addrs + +for interface, addrs in net_if_addrs().items(): + for addr in addrs: + if addr.family == 2: # AF_INET for IPv4 + print(f"Interface: {interface}, IP: {addr.address}, Netmask: {addr.netmask}") +``` + +---------------------------------------- + +TITLE: Process methods segfault on FreeBSD 12.0 +DESCRIPTION: Resolves a critical segfault issue affecting many Process methods on FreeBSD 12.0. This was caused by a backward-incompatible change in a C type, which has now been addressed. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_139 + +LANGUAGE: python +CODE: +``` +p.status() +# Many Process methods are now stable on FreeBSD 12.0. +``` + +---------------------------------------- + +TITLE: Process.cpu_affinity() segfault fix on CentOS 5 +DESCRIPTION: Addresses a critical segfault issue with Process.cpu_affinity() on CentOS 5 and manylinux environments. Support for CentOS 5 has been removed to resolve this instability. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_102 + +LANGUAGE: python +CODE: +``` +p.cpu_affinity() +# This operation was found to be unstable on older CentOS versions. +``` + +---------------------------------------- + +TITLE: Process Memory Info Return Type +DESCRIPTION: Changes the return type of `Process.memory_info()` from a tuple to a namedtuple. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_511 + +LANGUAGE: APIDOC +CODE: +``` +Process: + memory_info(): Returns memory usage statistics as a namedtuple (e.g., rss, vms). +``` + +---------------------------------------- + +TITLE: cpu_freq() None Return Handling (Linux) +DESCRIPTION: Modifies cpu_freq() behavior on Linux to not make the function available if it returns None on certain versions, preventing potential errors. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_230 + +LANGUAGE: python +CODE: +``` +# Original issue: [Linux]: cpu_freq() may return None on some Linux versions does not support the function. Let's not make the function available instead. +# This change prevents errors by not exposing cpu_freq() when it's unsupported. +``` + +---------------------------------------- + +TITLE: Process.oneshot() Thread Safety +DESCRIPTION: Ensures that the Process.oneshot() context manager is thread-safe, preventing potential race conditions and data corruption when used concurrently by multiple threads. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_176 + +LANGUAGE: python +CODE: +``` +# Process.oneshot() is now thread safe. +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes - Process.cpu_percent() Capping +DESCRIPTION: Removes the 100% cap on Process.cpu_percent() on Windows, allowing for accurate reporting of CPU usage on multi-core systems where a single process can utilize more than one core. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_431 + +LANGUAGE: python +CODE: +``` +# Fix for psutil.Process.cpu_percent() being capped at 100% on Windows +# Original issue: https://github.com/giampaolo/psutil/issues/474 +``` + +---------------------------------------- + +TITLE: Windows Memory Management Fix +DESCRIPTION: Includes a fix for Windows where a variable might be NULL before being freed, potentially causing memory errors. This ensures safer memory management. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_183 + +LANGUAGE: python +CODE: +``` +# [Windows]: check if variable is NULL before free()ing it. +``` + +---------------------------------------- + +TITLE: Distribution Size Reduction +DESCRIPTION: Reduces the size of the tar.gz distribution from 1.8MB to 258KB. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_264 + +LANGUAGE: python +CODE: +``` +# Enhancement: tar.gz distribution went from 1.8M to 258K. +# This makes the distribution package significantly smaller and faster to download. +``` + +---------------------------------------- + +TITLE: macOS Process Memory Maps Access Denied +DESCRIPTION: Fixes an issue on macOS where Process.memory_maps() could fail with EINVAL due to issues with the task_for_pid() syscall. AccessDenied is now raised instead, providing a more appropriate error. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_198 + +LANGUAGE: python +CODE: +``` +# [macOS]: Process.memory_maps() may fail with EINVAL due to poor task_for_pid() syscall. AccessDenied is now raised instead. +``` + +---------------------------------------- + +TITLE: Process.wait() Bug Fix (Windows) +DESCRIPTION: Addresses an issue on Windows where Process.wait() might return prematurely while the process is still alive. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_220 + +LANGUAGE: python +CODE: +``` +# Original issue: Process.wait() may erroneously return sooner, when the PID is still alive. +# Fix involves ensuring the wait condition accurately reflects process termination. +``` + +---------------------------------------- + +TITLE: Process.memory_maps() KeyError on Linux +DESCRIPTION: Addresses a KeyError that could occur in Process.memory_maps() on Linux. This improves the robustness of memory map retrieval. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_137 + +LANGUAGE: python +CODE: +``` +p.memory_maps() +# Now handles potential KeyErrors. +``` + +---------------------------------------- + +TITLE: Kill Process Tree +DESCRIPTION: This function recursively kills a process and all its descendants. It allows specifying a signal, whether to include the parent process, a timeout for termination, and an optional callback function to be executed when a child process terminates. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_95 + +LANGUAGE: python +CODE: +``` +import os +import signal +import psutil + +def kill_proc_tree(pid, sig=signal.SIGTERM, include_parent=True, + timeout=None, on_terminate=None): + """Kill a process tree (including grandchildren) with signal + "sig" and return a (gone, still_alive) tuple. + "on_terminate", if specified, is a callback function which is + called as soon as a child terminates. + """ + assert pid != os.getpid(), "won't kill myself" + parent = psutil.Process(pid) + children = parent.children(recursive=True) + if include_parent: + children.append(parent) + for p in children: + try: + p.send_signal(sig) + except psutil.NoSuchProcess: + pass + gone, alive = psutil.wait_procs(children, timeout=timeout, + callback=on_terminate) + return (gone, alive) +``` + +---------------------------------------- + +TITLE: Windows Process.name() Long Name AccessDenied Fix +DESCRIPTION: Fixes an issue on Windows where 32-bit / WoW64 processes with names longer than 128 characters would result in AccessDenied when calling Process.name(). This now correctly retrieves long process names. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_85 + +LANGUAGE: python +CODE: +``` +# Example of retrieving process name on Windows, including long names +# import psutil +# try: +# p = psutil.Process(pid) +# name = p.name() +# print(f"Process name: {name}") +# except psutil.AccessDenied: +# print("Access denied, possibly due to long process name (now fixed).") +# except psutil.NoSuchProcess: +# print("Process not found.") +``` + +---------------------------------------- + +TITLE: Wait for Processes to Terminate +DESCRIPTION: A utility function to wait for a list of `Process` instances to terminate. It returns a tuple of (gone, alive) processes and can execute a callback function when a process terminates. It handles timeouts gracefully without raising exceptions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_29 + +LANGUAGE: python +CODE: +``` +import psutil +import time + +def on_terminate(proc): + print(f"Process {proc.pid} terminated with exit code {proc.returncode}") + +# Example: Get children of the current process +child_procs = psutil.Process().children() + +# Terminate children and wait for them +for p in child_procs: + p.terminate() + +gone, alive = psutil.wait_procs(child_procs, timeout=5, callback=on_terminate) + +# Kill any remaining alive processes +for p in alive: + p.kill() +``` + +---------------------------------------- + +TITLE: Orphaned Process Handle Leak Fix (Windows) +DESCRIPTION: Fixes a bug on Windows where orphaned process handles were left behind when the `Process` class was instantiated. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_530 + +LANGUAGE: python +CODE: +``` +# Process handles are now correctly managed on Windows. +``` + +---------------------------------------- + +TITLE: psutil.wait_procs() Utility Function +DESCRIPTION: Introduced the `psutil.wait_procs()` utility function, which allows waiting for multiple processes to terminate. This is useful for managing and synchronizing the execution of child processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_445 + +LANGUAGE: python +CODE: +``` +import psutil +import subprocess + +# Start some processes +procs = [] +for _ in range(3): + procs.append(subprocess.Popen(['sleep', '5'])) + +# Wait for all processes to terminate +# The second element of the tuple is the return code +results = psutil.wait_procs(procs, timeout=None) + +for p, retcode in results: + print(f"Process {p.pid()} finished with return code: {retcode}") +``` + +---------------------------------------- + +TITLE: Process Memory/Handle Leak Fix on Windows +DESCRIPTION: Addresses memory and handle leaks in Process.memory_info(), Process.suspend(), and Process.resume() methods on Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_473 + +LANGUAGE: python +CODE: +``` +# Fix for memory/handle leaks in Process methods on Windows. +``` + +---------------------------------------- + +TITLE: Add sensors_fans() Function (Linux) +DESCRIPTION: Introduces the sensors_fans() function for Linux systems to retrieve fan speed information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_237 + +LANGUAGE: python +CODE: +``` +# Enhancement: [Linux]: Add sensors_fans() function. +# This function provides access to system fan speeds. +``` + +---------------------------------------- + +TITLE: Process.io_counters() New Fields (Windows/Linux) +DESCRIPTION: Adds two new fields, 'other_count' and 'other_bytes', to Process.io_counters() on Windows, and 'read_chars' and 'write_chars' on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_238 + +LANGUAGE: python +CODE: +``` +# Enhancement: [Windows]: Process.io_counters() has 2 new fields: 'other_count' and 'other_bytes'. +# Enhancement: [Linux]: Process.io_counters() has 2 new fields: 'read_chars' and 'write_chars'. +# These additions provide more detailed I/O statistics. +``` + +---------------------------------------- + +TITLE: Process.cpu_times() macOS Incorrect Timings +DESCRIPTION: Fixes an issue where Process.cpu_times() reports incorrect timings on macOS M1 machines. This patch addresses inaccuracies in CPU time reporting on Apple Silicon. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_86 + +LANGUAGE: APIDOC +CODE: +``` +Process.cpu_times() + - Reports incorrect timings on macOS M1 machines. + - Fixed by Olivier Dormond. +``` + +---------------------------------------- + +TITLE: Process.terminate() Access Denied Fix (Windows) +DESCRIPTION: Resolves an AccessDenied error in Process.terminate() on Windows, even when the process has already terminated. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_221 + +LANGUAGE: python +CODE: +``` +# Original issue: Process.terminate() may raise AccessDenied even if the process already died. +# Fix ensures proper handling of already terminated processes to avoid AccessDenied exceptions. +``` + +---------------------------------------- + +TITLE: Process.parents() Method Addition +DESCRIPTION: Adds a new method to retrieve the parent processes of a given process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_164 + +LANGUAGE: python +CODE: +``` +Process.parents() +``` + +---------------------------------------- + +TITLE: Cross-Platform Network Interface Stats Error Handling +DESCRIPTION: Addresses an issue on Linux, macOS, and BSD systems where net_if_stats() might return ENODEV. This ensures more consistent behavior across different platforms. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_200 + +LANGUAGE: python +CODE: +``` +# [Linux], [macOS], [BSD]: net_if_stats() may return ENODEV. +``` + +---------------------------------------- + +TITLE: Process.cpu_affinity() ValueError for [-1] (Linux) +DESCRIPTION: Ensures that passing [-1] to Process.cpu_affinity() on Linux raises a ValueError instead of a SystemError, improving error handling. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_300 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +try: + p = Process() + p.cpu_affinity([-1]) +except ValueError as e: + print(f"Correctly caught ValueError: {e}") +except Exception as e: + print(f"Caught unexpected exception: {e}") +``` + +---------------------------------------- + +TITLE: cpu_affinity() PyList_Append Check Fix on Linux +DESCRIPTION: Ensures that PyList_Append and Py_BuildValue return values are checked in the alternative implementation of Process.cpu_affinity() on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_384 + +LANGUAGE: python +CODE: +``` +# Original issue: in the alternative implementation of Process.cpu_affinity() PyList_Append and Py_BuildValue return values are not checked on Linux. +# Fix implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: Process.exe() error on Windows +DESCRIPTION: Resolves a critical issue on Windows where Process.exe() could raise a '[WinError 0] The operation completed successfully' error. This ensures the executable path is retrieved correctly. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_113 + +LANGUAGE: python +CODE: +``` +p.exe() +# No longer raises spurious success errors. +``` + +---------------------------------------- + +TITLE: Can't import psutil on SunOS +DESCRIPTION: Resolves a critical issue preventing psutil from being imported on SunOS systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_416 + +LANGUAGE: python +CODE: +``` +# Original issue: can't import psutil on SunOS. +# Fix implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: Linux Disk I/O Counters Compatibility +DESCRIPTION: Fixes an issue where disk_io_counters() would fail on Linux kernel versions 4.18 and later. This ensures continued functionality with newer kernel versions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_177 + +LANGUAGE: python +CODE: +``` +# [Linux]: disk_io_counters() fails on Linux kernel 4.18+. +``` + +---------------------------------------- + +TITLE: PID 0 Omission Fix (OpenBSD) +DESCRIPTION: Corrects an issue on OpenBSD where PID 0 was omitted by the pids() function. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_314 + +LANGUAGE: python +CODE: +``` +from psutil import pids + +all_pids = pids() +# PID 0 should now be included in the list if it exists. +# print(all_pids) +``` + +---------------------------------------- + +TITLE: Windows Handle Usage Error Handling +DESCRIPTION: Improves error handling in Windows by ensuring that the original error code is preserved when raising an exception after improper usage of CloseHandle(). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_180 + +LANGUAGE: python +CODE: +``` +# [Windows]: improper usage of CloseHandle() may lead to override the original error code when raising an exception. +``` + +---------------------------------------- + +TITLE: Windows disk_partitions() Buffer Length Crash Fix +DESCRIPTION: Fixes a critical crash on Windows related to disk_partitions() due to insufficient buffer length. This ensures stable disk partition reporting. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_83 + +LANGUAGE: python +CODE: +``` +# Example of retrieving disk partitions on Windows +# import psutil +# try: +# partitions = psutil.disk_partitions() +# print(f"Found {len(partitions)} disk partitions.") +# except Exception as e: +# print(f"Error retrieving disk partitions: {e}") +``` + +---------------------------------------- + +TITLE: sensors_temperatures() CentOS 7 Fix (Linux) +DESCRIPTION: Resolves an issue where sensors_temperatures() did not function correctly on CentOS 7. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_242 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Linux]: sensors_temperatures() didn't work on CentOS 7. +# This ensures temperature monitoring works on CentOS 7. +``` + +---------------------------------------- + +TITLE: UID/GID Change Handling Fix +DESCRIPTION: Fixes an issue where `uid` and `gid` properties did not update if a process changed its effective user/group ID. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_533 + +LANGUAGE: python +CODE: +``` +p.uids() +p.gids() +``` + +---------------------------------------- + +TITLE: macOS cpu_freq() Min/Max Default to 0 Fix +DESCRIPTION: Fixes a critical issue on macOS where cpu_freq() would set 'min' and 'max' frequencies to 0 if they couldn't be determined, preventing crashes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_71 + +LANGUAGE: python +CODE: +``` +# Example of retrieving CPU frequency on macOS +# import psutil +# freq = psutil.cpu_freq() +# if freq: +# print(f"CPU Freq - Current: {freq.current}, Min: {freq.min}, Max: {freq.max}") +``` + +---------------------------------------- + +TITLE: disk_io_counters() Sector Size Calculation Fix (Linux) +DESCRIPTION: Corrects miscalculations in sector size for disk_io_counters() on Linux, leading to accurate byte counts for read and written data. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_249 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Linux]: disk_io_counters() may miscalculate sector size and report the wrong number of bytes read and written. +# This ensures accurate disk I/O statistics. +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes - pid_exists() for PID 0 +DESCRIPTION: Corrects the behavior of pid_exists() on POSIX systems, ensuring it returns False for PID 0, which is a reserved value and not a valid process ID. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_425 + +LANGUAGE: python +CODE: +``` +# Fix for psutil.pid_exists() always returning True for PID 0 on POSIX +# Original issue: https://github.com/giampaolo/psutil/issues/457 +``` + +---------------------------------------- + +TITLE: Process.memory_info_ex() USS Calculation Fix (Windows) +DESCRIPTION: Corrects the miscalculation of USS memory in Process.memory_info_ex() on Windows by using the actual system PAGESIZE. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_168 + +LANGUAGE: python +CODE: +``` +Process.memory_info_ex() +``` + +---------------------------------------- + +TITLE: Bytes to Human-Readable Format Conversion +DESCRIPTION: A utility function to convert bytes into a human-readable format (e.g., KB, MB, GB). It uses a predefined set of symbols and calculates the appropriate unit and value for the given number of bytes. This is useful for displaying file sizes or disk usage. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_101 + +LANGUAGE: python +CODE: +``` +import psutil + +def bytes2human(n): + # http://code.activestate.com/recipes/578019 + # >>> bytes2human(10000) + # '9.8K' + # >>> bytes2human(100001221) + # '95.4M' + symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') + prefix = {} + for i, s in enumerate(symbols): + prefix[s] = 1 << (i + 1) * 10 + for s in reversed(symbols): + if abs(n) >= prefix[s]: + value = float(n) / prefix[s] + return '%.1f%s' % (value, s) + return "%sB" % n + +total = psutil.disk_usage('/').total +print(total) +print(bytes2human(total)) +``` + +---------------------------------------- + +TITLE: sensors_temperatures() OSError Handling (Linux) +DESCRIPTION: Addresses OSError exceptions that might be raised by sensors_temperatures() on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_231 + +LANGUAGE: python +CODE: +``` +# Original issue: [Linux]: sensors_temperatures() may raise OSError. +# This fix improves robustness by handling potential OS errors. +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes - psutil.Popen.wait() Return Code +DESCRIPTION: Fixes an issue where the wait() method of psutil.Popen might not set the returncode attribute correctly after process termination. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_430 + +LANGUAGE: python +CODE: +``` +# Fix for psutil.Popen.wait() not setting returncode attribute +# Original issue: https://github.com/giampaolo/psutil/issues/473 +``` + +---------------------------------------- + +TITLE: psutil Compilation Fixes +DESCRIPTION: psutil compilation issues have been addressed for various platforms and configurations, including GCC versions on macOS, mips64 on OpenBSD, and NetBSD-6.x. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_339 + +LANGUAGE: python +CODE: +``` +# Compilation fix example (no specific code snippet) +``` + +---------------------------------------- + +TITLE: Process.cpu_times() Enhancements +DESCRIPTION: Process.cpu_times() now returns two new fields: 'children_user' and 'children_system'. These fields represent CPU time spent by child processes. Note that these are always set to 0 on macOS and Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_322 + +LANGUAGE: python +CODE: +``` +process.cpu_times() +``` + +---------------------------------------- + +TITLE: Process Terminal Association +DESCRIPTION: Returns the terminal associated with the process, if any. If no terminal is associated, it returns `None`. This functionality is available on UNIX systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_49 + +LANGUAGE: APIDOC +CODE: +``` +.. method:: terminal() + + The terminal associated with this process, if any, else ``None``. This is + similar to "tty" command but can be used for any process PID. + + Availability: UNIX +``` + +---------------------------------------- + +TITLE: net_connections() Segfault Fix +DESCRIPTION: Fixes a segfault in the net_connections() function, noted as a critical issue. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_368 + +LANGUAGE: python +CODE: +``` +# Original issue: fix segfault in net_connections(). +# Fix implemented in psutil version 2.1.0 +``` + +---------------------------------------- + +TITLE: Process Executable Path Type Error (Linux Fix) +DESCRIPTION: Fixes a `TypeError` that could be raised by `Process.exe()` on Linux if the path contained NULL bytes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_507 + +LANGUAGE: python +CODE: +``` +p.exe() +``` + +---------------------------------------- + +TITLE: Process.exe() error on Windows +DESCRIPTION: Resolves a critical issue on Windows where Process.exe() could raise a '[WinError 0] The operation completed successfully' error. This ensures the executable path is retrieved correctly. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_142 + +LANGUAGE: python +CODE: +``` +p.exe() +# No longer raises spurious success errors. +``` + +---------------------------------------- + +TITLE: AIX CPU Times Unit Correction +DESCRIPTION: Fixes an issue on AIX where system CPU times (cpu_times()) were reported in ticks instead of seconds, ensuring correct time unit reporting. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_192 + +LANGUAGE: python +CODE: +``` +# [AIX]: system CPU times (cpu_times()) were being reported with ticks unit as opposed to seconds. +``` + +---------------------------------------- + +TITLE: Visual Studio Compilation Fix (Windows) +DESCRIPTION: Fixes an issue preventing psutil from compiling with Visual Studio on Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_527 + +LANGUAGE: python +CODE: +``` +# psutil now compiles correctly with Visual Studio on Windows. +``` + +---------------------------------------- + +TITLE: users() Encoding Fix on Windows +DESCRIPTION: Ensures proper encoding is used for users() on Windows systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_376 + +LANGUAGE: python +CODE: +``` +# Original issue: use proper encoding for users() on Windows. +# Fix implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: Process.io_counters() ValueError Handling (Linux) +DESCRIPTION: Handles potential ValueError exceptions that may occur with Process.io_counters() on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_229 + +LANGUAGE: python +CODE: +``` +# Original issue: [Linux]: Process.io_counters() may raise ValueError. +# This fix ensures the function handles invalid data gracefully. +``` + +---------------------------------------- + +TITLE: disk_io_counters() Negative Value Fix on Windows +DESCRIPTION: Corrects an issue on Windows where disk_io_counters() could return negative values. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_392 + +LANGUAGE: python +CODE: +``` +# Original issue: disk_io_counters() may return negative values on Windows. +# Fix implemented in psutil version 2.1.2 +``` + +---------------------------------------- + +TITLE: Process UID/GID Property Deprecation +DESCRIPTION: Deprecates the `uid` and `gid` properties of the `Process` class in favor of the new `uids` and `gids` properties. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_509 + +LANGUAGE: APIDOC +CODE: +``` +Process: + uid: Deprecated alias for uids + gid: Deprecated alias for gids + uids(): Returns a tuple of (real, effective, saved) user IDs. + gids(): Returns a tuple of (real, effective, saved) group IDs. +``` + +---------------------------------------- + +TITLE: cpu_percent() Timeout Default Change +DESCRIPTION: Changes the default timeout parameter for cpu_percent* functions to 0.0 to prevent accidental slowdowns. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_385 + +LANGUAGE: python +CODE: +``` +# Enhancement: make timeout parameter of "cpu_percent*" functions default to "0.0" 'cause it's a common trap to introduce slowdowns. +# Implemented in psutil version 2.0.0 +``` + +---------------------------------------- + +TITLE: CPU Times Return Type +DESCRIPTION: Changes the return type of `cpu_times()` from a tuple to a namedtuple. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_512 + +LANGUAGE: APIDOC +CODE: +``` +psutil: + cpu_times(): Returns system CPU times as a namedtuple (e.g., user, system, idle). +``` + +---------------------------------------- + +TITLE: POSIX Compilation with g++ +DESCRIPTION: Improves compilation support on POSIX systems when using g++ instead of GCC, ensuring broader compiler compatibility. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_186 + +LANGUAGE: python +CODE: +``` +# [POSIX]: better compilation support when using g++ instead of GCC. +``` + +---------------------------------------- + +TITLE: psutil Compilation on Solaris +DESCRIPTION: psutil compilation and tests have been fixed on Solaris 10 and Solaris sparc. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_348 + +LANGUAGE: python +CODE: +``` +# Compilation fix example (no specific code snippet) +``` + +---------------------------------------- + +TITLE: POSIX net_if_stats() Flags Unicode to String Conversion +DESCRIPTION: Corrects an issue on POSIX systems where the 'flags' field in net_if_stats() returned unicode instead of str on Python 2. This ensures consistent string handling. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_48 + +LANGUAGE: python +CODE: +``` +# Example of handling net_if_stats() flags on POSIX systems +# import psutil +# for interface, stats in psutil.net_if_stats().items(): +# flags = stats.flags +# if isinstance(flags, bytes): +# flags = flags.decode('utf-8') # or appropriate encoding +# print(f"Interface: {interface}, Flags: {flags}") +``` + +---------------------------------------- + +TITLE: Process.wait() with timeout=0 +DESCRIPTION: Allows Process.wait() with timeout=0 to return immediately, useful for non-blocking checks. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_476 + +LANGUAGE: python +CODE: +``` +# Non-blocking wait: +process.wait(timeout=0) +``` + +---------------------------------------- + +TITLE: Process Children +DESCRIPTION: Retrieves the child processes of the current process. If `recursive` is set to True, it returns all descendants of the process. Note that if a parent process disappears, its children may also become inaccessible. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_74 + +LANGUAGE: python +CODE: +``` +import psutil +p = psutil.Process() +# Get direct children +children = p.children() +# Get all descendants +all_descendants = p.children(recursive=True) +``` + +---------------------------------------- + +TITLE: PID Existence Check +DESCRIPTION: Mentions the `pid_exists()` function for checking if a process ID is currently active. It includes a special case for PID 0 on Linux and macOS. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_556 + +LANGUAGE: python +CODE: +``` +pid_exists(pid) +``` + +---------------------------------------- + +TITLE: Linux Disk I/O Counters Value Inflation Fix +DESCRIPTION: Fixes an issue on Linux where disk_io_counters() could report inflated read/write byte values. This ensures more accurate disk I/O statistics. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_202 + +LANGUAGE: python +CODE: +``` +# [Linux]: disk_io_counters() may report inflated r/w bytes values. +``` + +---------------------------------------- + +TITLE: net_connections() Race Condition Fix (Windows) +DESCRIPTION: Fixes a race condition within the net_connections() function on Windows, improving its reliability. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_310 + +LANGUAGE: python +CODE: +``` +from psutil import net_connections + +try: + connections = net_connections() + print(f"Retrieved {len(connections)} network connections.") +except Exception as e: + print(f"An error occurred: {e}") +``` + +---------------------------------------- + +TITLE: disk_io_counters() Enhancements +DESCRIPTION: On Linux and FreeBSD, disk_io_counters() now returns a new field 'busy_time'. Additionally, on Linux, it returns 'read_merged_count' and 'write_merged_count'. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_325 + +LANGUAGE: python +CODE: +``` +psutil.disk_io_counters() +``` + +---------------------------------------- + +TITLE: Windows String Type Changes (Python 2) +DESCRIPTION: Specifies that certain Windows API string return types are now bytes instead of unicode in Python 2 for consistency. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_226 + +LANGUAGE: python +CODE: +``` +# Original issue: the following Windows APIs on Python 2 now return a string instead of unicode: +# Process.memory_maps().path, WindowsService.bin_path(), WindowsService.description(), +# WindowsService.display_name(), WindowsService.username(). +# This change aligns return types with Python 2's string handling. +``` + +---------------------------------------- + +TITLE: sensors_battery() Bytes vs Str Fix (Linux) +DESCRIPTION: Ensures that 'name' and 'label' fields from sensors_battery() on Linux return strings instead of bytes in Python 3. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_246 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Linux]: sensors_battery() 'name' and 'label' fields on Python 3 are bytes instead of str. +# This change ensures consistent string representation for battery information. +``` + +---------------------------------------- + +TITLE: Process.username() Encoding Fix on Windows +DESCRIPTION: Ensures proper encoding is used for Process.username() on Windows systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_374 + +LANGUAGE: python +CODE: +``` +# Original issue: use proper encoding for Process.username() on Windows. +# Fix implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: cpu_count() Memory Leak Fix on FreeBSD +DESCRIPTION: Addresses a memory leak in cpu_count() when logical=False is used on FreeBSD. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_381 + +LANGUAGE: python +CODE: +``` +# Original issue: fix memory leak in cpu_count() with logical=False on FreeBSD. +# Fix implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: Linux Virtual Memory Slab Field Exposure +DESCRIPTION: Enhances virtual_memory() on Linux by exposing the kernel 'slab' memory field, providing more detailed memory usage information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_210 + +LANGUAGE: python +CODE: +``` +# [Linux]: expose kernel "slab" memory field for virtual_memory(). +``` + +---------------------------------------- + +TITLE: virtual_memory() ValueError Handling (Linux) +DESCRIPTION: Handles ValueError exceptions that can occur with virtual_memory() on Ubuntu 14.04. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_232 + +LANGUAGE: python +CODE: +``` +# Original issue: [Linux]: virtual_memory() may raise ValueError on Ubuntu 14.04. +# This change ensures the function works correctly on the specified Ubuntu version. +``` + +---------------------------------------- + +TITLE: Process.memory_maps() UnicodeDecodeError Handling (Windows) +DESCRIPTION: Resolves UnicodeDecodeError exceptions that can occur with Process.memory_maps() on Windows with Python 3. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_234 + +LANGUAGE: python +CODE: +``` +# Original issue: [Windows]: Process.memory_maps() on Python 3 may raise UnicodeDecodeError. +# This fix ensures correct decoding of memory map information. +``` + +---------------------------------------- + +TITLE: memoize_when_activated Decorator Thread-Safety Fix +DESCRIPTION: Fixes a critical issue where the 'memoize_when_activated' decorator was not thread-safe. This ensures correct behavior in multi-threaded environments. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_82 + +LANGUAGE: python +CODE: +``` +# Example of a function potentially using the memoize_when_activated decorator +# (Decorator usage is internal to psutil's implementation) +# @psutil._common.memoize_when_activated +# def some_cached_function(): +# # ... function logic ... +# pass +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes - Process.exe() Unicode Handling on Windows +DESCRIPTION: Resolves improper Unicode handling in Process.exe() on Windows, ensuring correct processing of non-ASCII executable paths. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_429 + +LANGUAGE: python +CODE: +``` +# Fix for improper unicode handling in psutil.Process.exe() on Windows +# Original issue: https://github.com/giampaolo/psutil/issues/471 +``` + +---------------------------------------- + +TITLE: File handles left open on Linux +DESCRIPTION: Fixes a bug on Linux where numerous file handles were left open, potentially causing resource exhaustion. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_417 + +LANGUAGE: python +CODE: +``` +# Original issue: lots of file handles were left open on Linux. +# Fix implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: Test C Extension Memory Leaks +DESCRIPTION: Runs tests specifically designed to detect memory leaks in the C extension modules of psutil. Requires the source code. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/psutil/tests/README.rst#_snippet_4 + +LANGUAGE: bash +CODE: +``` +make test-memleaks +``` + +---------------------------------------- + +TITLE: Process CPU Times +DESCRIPTION: Retrieves CPU time spent by the process in user and kernel mode, including child processes and I/O wait times. The first call might return 0.0 for non-blocking CPU percentage. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_62 + +LANGUAGE: python +CODE: +``` +import psutil +p = psutil.Process() +print(p.cpu_times()) +print(sum(p.cpu_times()[:2])) +``` + +---------------------------------------- + +TITLE: Linux Disk I/O Counters Double Counting Fix +DESCRIPTION: Corrects an issue on Linux where disk_io_counters() could report inflated values due to double-counting base disk devices and their partitions. This ensures accurate disk I/O metrics. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_204 + +LANGUAGE: python +CODE: +``` +# [Linux]: disk_io_counters() can report inflated values due to counting base disk device and its partition(s) twice. +``` + +---------------------------------------- + +TITLE: net_if_stats() Additional Flags Added +DESCRIPTION: Enhances the net_if_stats() function by adding support for additional interface flags, providing more detailed network interface information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_57 + +LANGUAGE: python +CODE: +``` +# Example of accessing additional flags from net_if_stats() +# import psutil +# for interface, stats in psutil.net_if_stats().items(): +# print(f"Interface: {interface}, Flags: {stats.flags}") # Accessing flags +``` + +---------------------------------------- + +TITLE: Windows OpenProcess GetLastError() Fix +DESCRIPTION: Fixes an issue on Windows where OpenProcess could fail with ERROR_SUCCESS due to GetLastError() being called after sprintf(). This ensures correct error handling for process opening. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_77 + +LANGUAGE: python +CODE: +``` +# Conceptual: This fix is within the C extension of psutil for Windows. +# User code interacting with process handles should now be more reliable. +``` + +---------------------------------------- + +TITLE: net_io_counters() Unicode Hack Removal on Windows +DESCRIPTION: Removes a unicode hack for NIC names in net_io_counters() on Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_387 + +LANGUAGE: python +CODE: +``` +# Original issue: get rid of the unicode hack for net_io_counters() NIC names on Windows. +# Fix implemented in psutil version 2.2.0 +``` + +---------------------------------------- + +TITLE: Process Name +DESCRIPTION: Retrieves the name of the process. On Windows, the return value is cached after the first call. On POSIX systems, the process name may change, so it is not cached. This method can be used to find a process by name. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_37 + +LANGUAGE: APIDOC +CODE: +``` +name() + Returns the process name. + On Windows the return value is cached after first call. + Not on POSIX because the process name may change. + See also how to `find a process by name <#find-process-by-name>`__. + Returns: The process name. +``` + +---------------------------------------- + +TITLE: Process Memory Info Handle Leak (Windows) +DESCRIPTION: Fixes a handle leak issue on Windows related to `Process.memory_info()`. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_538 + +LANGUAGE: python +CODE: +``` +p.memory_info() +``` + +---------------------------------------- + +TITLE: virtual_memory() Fixes +DESCRIPTION: On FreeBSD, virtual_memory() 'total' value is no longer incorrect. On NetBSD, the 'cached' value was always set to 0 and is now fixed. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_337 + +LANGUAGE: python +CODE: +``` +psutil.virtual_memory() +``` + +---------------------------------------- + +TITLE: virtual_memory() Accuracy on macOS +DESCRIPTION: Bug fix for psutil version 7.0.0: virtual_memory() on macOS now relies on host_statistics64 for more accurate results, similar to the vm_stat CLI tool. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_21 + +LANGUAGE: python +CODE: +``` +import psutil + +# Example usage +# mem = psutil.virtual_memory() +# print(f"Total: {mem.total}, Available: {mem.available}") +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes - wait_procs() Waiting Behavior +DESCRIPTION: Corrects potential issues where wait_procs() might not wait as expected, ensuring reliable process monitoring. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_428 + +LANGUAGE: python +CODE: +``` +# Fix for psutil.wait_procs() potentially not waiting correctly +# Original issue: https://github.com/giampaolo/psutil/issues/470 +``` + +---------------------------------------- + +TITLE: sensors_battery() FileNotFoundError Handling (Linux) +DESCRIPTION: Handles FileNotFoundError exceptions that may occur with sensors_battery() on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_250 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Linux]: sensors_battery() may fail with FileNotFoundError. +# This improves the robustness of battery monitoring. +``` + +---------------------------------------- + +TITLE: Process.wait() Timeout Unit Fix (Windows) +DESCRIPTION: Corrects the timeout unit for Process.wait() on Windows, ensuring it uses seconds instead of milliseconds, preventing incorrect timeout behavior. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_306 + +LANGUAGE: python +CODE: +``` +from psutil import Process, TimeoutExpired + +try: + p = Process() + # Wait for 10 seconds + p.wait(timeout=10) +except TimeoutExpired: + print("TimeoutExpired caught correctly with seconds.") +except Exception as e: + print(f"An error occurred: {e}") +``` + +---------------------------------------- + +TITLE: psutil Import Time Stability +DESCRIPTION: psutil will no longer crash at import time if cpu_times() fails for any reason. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_345 + +LANGUAGE: python +CODE: +``` +import psutil +``` + +---------------------------------------- + +TITLE: Linux ENAMETOOLONG Handling in Procfs +DESCRIPTION: Ensures that psutil correctly handles the ENAMETOOLONG error when accessing process file descriptors in procfs on Linux. This prevents failures when dealing with very long file descriptor names. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_81 + +LANGUAGE: python +CODE: +``` +# Conceptual: psutil internally handles ENAMETOOLONG for procfs access. +# User code interacting with process file descriptors should be more robust. +``` + +---------------------------------------- + +TITLE: Check if PID Exists +DESCRIPTION: Efficiently checks if a given PID exists in the current process list. This method is faster than checking membership in the list returned by `psutil.pids()`. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_28 + +LANGUAGE: python +CODE: +``` +import psutil + +pid_to_check = 1234 + +if psutil.pid_exists(pid_to_check): + print(f"PID {pid_to_check} exists.") +else: + print(f"PID {pid_to_check} does not exist.") +``` + +---------------------------------------- + +TITLE: Race Condition in net_connections() (Windows) +DESCRIPTION: Fixes a race condition within the net_connections() function on Windows, improving its stability and reliability. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_319 + +LANGUAGE: python +CODE: +``` +from psutil import net_connections + +try: + connections = net_connections() + print(f"Retrieved {len(connections)} connections.") +except Exception as e: + print(f"An error occurred: {e}") +``` + +---------------------------------------- + +TITLE: memory_leak Fix (Windows) +DESCRIPTION: Addresses memory leaks found in cpu_stats() and the WindowsService.description() method on Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_316 + +LANGUAGE: python +CODE: +``` +from psutil import cpu_stats +from psutil import WindowsService + +# Example usage that previously might have caused a leak +# cpu_stats() +# svc = WindowsService('YourServiceName') +# svc.description() +``` + +---------------------------------------- + +TITLE: macOS Process.cmdline() Test Race Condition Fix +DESCRIPTION: Fixes a race condition identified in the test_posix.TestProcess.test_cmdline test case on macOS, improving test reliability. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_51 + +LANGUAGE: python +CODE: +``` +# Conceptual test scenario for Process.cmdline() on macOS +# import psutil +# import unittest +# class TestProcessCmdline(unittest.TestCase): +# def test_cmdline_race_condition(self): +# # Test logic to trigger and verify cmdline behavior under race conditions +# pass +``` + +---------------------------------------- + +TITLE: Process.wait() Return Value Cached +DESCRIPTION: The return value of Process.wait() is now cached, allowing the exit code to be retrieved on subsequent calls. This improves the reliability of retrieving process exit codes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_94 + +LANGUAGE: APIDOC +CODE: +``` +Process.wait() + - Return value is cached so that the exit code can be retrieved on the next call. +``` + +---------------------------------------- + +TITLE: disk_io_counters() Fixes +DESCRIPTION: On FreeBSD, disk_io_counters() r/w times are now expressed in milliseconds instead of seconds. On Linux, it no longer raises ValueError on 2.6 kernels and is fixed on 2.4 kernels. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_341 + +LANGUAGE: python +CODE: +``` +psutil.disk_io_counters() +``` + +---------------------------------------- + +TITLE: Process.memory_maps() Segfault Fix (macOS) +DESCRIPTION: Fixes a critical bug on macOS where Process.memory_maps() could lead to a segmentation fault. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_296 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +try: + p = Process() + maps = p.memory_maps() + print("Successfully retrieved memory maps.") +except Exception as e: + print(f"An error occurred: {e}") +``` + +---------------------------------------- + +TITLE: Process Kill Method Change +DESCRIPTION: Removes the `signal` argument from `Process.kill()`. Use `Process.send_signal()` for sending signals. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_510 + +LANGUAGE: APIDOC +CODE: +``` +Process: + kill(): Terminates the process. + send_signal(signal): + Sends a signal to the process. + Parameters: + signal: The signal to send (e.g., signal.SIGTERM). +``` + +---------------------------------------- + +TITLE: Process.connections() Memory Leak Fix +DESCRIPTION: Fixes a memory leak in Process.connections() on Windows and macOS. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_471 + +LANGUAGE: python +CODE: +``` +# Fix for memory leak in Process.connections() on Windows/macOS. +``` + +---------------------------------------- + +TITLE: Linux wait_procs() TimeoutExpired Handling +DESCRIPTION: Ensures that wait_procs() on Linux correctly catches subprocess.TimeoutExpired exceptions, improving robustness when waiting for processes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_78 + +LANGUAGE: python +CODE: +``` +# Example of using wait_procs() with timeout handling +# import psutil +# import time +# try: +# # Simulate waiting for a process with a timeout +# pids_to_wait = [12345] # Example PID +# psutil.wait_procs(pids_to_wait, timeout=5) +# except psutil.TimeoutExpired: +# print("Waiting for process timed out.") +# except Exception as e: +# print(f"An error occurred: {e}") +``` + +---------------------------------------- + +TITLE: psutil does not compile on SunOS 5.10 +DESCRIPTION: Fixes a critical compilation issue preventing psutil from compiling on SunOS 5.10. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_415 + +LANGUAGE: python +CODE: +``` +# Original issue: psutil does not compile on SunOS 5.10. +# Fix implemented in psutil version 2.1.0 +``` + +---------------------------------------- + +TITLE: Process.cpu_affinity() Socket Usage Fix (Linux) +DESCRIPTION: Fixes a potential double close and use of unopened socket within Process.cpu_affinity() on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_299 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +try: + p = Process() + # Example usage that might have caused the issue + p.cpu_affinity([0, 1]) + print("CPU affinity set successfully.") +except Exception as e: + print(f"An error occurred: {e}") +``` + +---------------------------------------- + +TITLE: Fix Build Issue on macOS 11 and Lower +DESCRIPTION: Bug fix for psutil version 7.0.1: Addressing a build issue on macOS 11 and earlier versions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_3 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to build system changes. +``` + +---------------------------------------- + +TITLE: Process.as_dict() Attribute Handling +DESCRIPTION: Modifies Process.as_dict() to ignore extraneous attribute names that might be passed, preventing errors and ensuring only valid attributes are processed. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_287 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +p = Process() +# Passing an invalid attribute name should be ignored gracefully +process_info = p.as_dict(attrs=['pid', 'name', 'non_existent_attr']) +print(process_info) +``` + +---------------------------------------- + +TITLE: disk_io_counters() on Linux kernels +DESCRIPTION: Updates disk_io_counters() on Linux to account for extra fields present in recent kernel versions. This ensures more comprehensive disk I/O statistics are collected. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_143 + +LANGUAGE: python +CODE: +``` +psutil.disk_io_counters() +# Now includes additional fields from newer kernels. +``` + +---------------------------------------- + +TITLE: NoSuchProcess PID Reuse Message Improvement +DESCRIPTION: Enhances the NoSuchProcess exception message to specify if the Process ID (PID) has been reused, providing clearer context for process-related errors. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_65 + +LANGUAGE: python +CODE: +``` +# Example of catching NoSuchProcess and checking for PID reuse +# import psutil +# try: +# p = psutil.Process(12345) +# # ... operations on process ... +# except psutil.NoSuchProcess as e: +# print(f"Process error: {e}") # Message will indicate if PID was reused +``` + +---------------------------------------- + +TITLE: net_io_counters() Swapped Values on SunOS +DESCRIPTION: Corrects an issue on SunOS where send and received values in net_io_counters() were swapped. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_386 + +LANGUAGE: python +CODE: +``` +# Original issue: net_io_counters() has send and received swapped on SunOS. +# Fix implemented in psutil version 2.1.0 +``` + +---------------------------------------- + +TITLE: disk_partitions() OSError on SunOS +DESCRIPTION: Addresses an issue on SunOS where disk_partitions() could raise an OSError. This improves the reliability of retrieving disk partition information on this platform. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_146 + +LANGUAGE: python +CODE: +``` +psutil.disk_partitions() +# Now more robust on SunOS. +``` + +---------------------------------------- + +TITLE: Process Wait Functionality +DESCRIPTION: Adds the ability to wait for a process to terminate and retrieve its exit code. Handles potential timeouts. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_493 + +LANGUAGE: python +CODE: +``` +p.wait(timeout=None) +``` + +---------------------------------------- + +TITLE: sensors_battery() power_plugged None Fix (Linux) +DESCRIPTION: Corrects an issue on Linux where sensors_battery() 'power_plugged' might erroneously return None on Python 3. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_244 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Linux]: sensors_battery() 'power_plugged' may erroneously return None on Python 3. +# This ensures the 'power_plugged' status is correctly reported. +``` + +---------------------------------------- + +TITLE: disk_io_counters() on Linux kernels +DESCRIPTION: Updates disk_io_counters() on Linux to account for extra fields present in recent kernel versions. This ensures more comprehensive disk I/O statistics are collected. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_114 + +LANGUAGE: python +CODE: +``` +psutil.disk_io_counters() +# Now includes additional fields from newer kernels. +``` + +---------------------------------------- + +TITLE: Linux Sensor Temperatures Parsing +DESCRIPTION: Improves sensors_temperatures() on Linux by enabling it to parse /sys/class/thermal when /sys/class/hwmon is not available, which is common on devices like Raspberry Pi. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_185 + +LANGUAGE: python +CODE: +``` +# [Linux]: sensors_temperatures() now parses /sys/class/thermal in case /sys/class/hwmon fs is not available (e.g. Raspberry Pi). +``` + +---------------------------------------- + +TITLE: Iterating Over Processes +DESCRIPTION: Details the `process_iter()` function, which provides an efficient way to iterate over all running processes on the system, yielding `Process` objects. This uses a generator for memory efficiency. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_553 + +LANGUAGE: python +CODE: +``` +process_iter() +``` + +---------------------------------------- + +TITLE: net_io_counters() Encoding Error Fix on Windows +DESCRIPTION: Fixes an encoding error when using net_io_counters() on Python 3 for Windows. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_388 + +LANGUAGE: python +CODE: +``` +# Original issue: fix encoding error when using net_io_counters() on Python 3 on Windows. +# Fix implemented in psutil version 2.1.1 +``` + +---------------------------------------- + +TITLE: Process.iter() Performance Improvement and Cache Clearing +DESCRIPTION: The process_iter() function no longer pre-emptively checks for PID reuse, making it approximately 20 times faster. A new API, psutil.process_iter.cache_clear(), is introduced to clear the internal cache. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_34 + +LANGUAGE: python +CODE: +``` +# Iterate through processes without pre-emptive PID reuse check +for proc in psutil.process_iter(): + # Process the process information + pass + +# Clear the internal cache of process_iter +psutil.process_iter.cache_clear() +``` + +---------------------------------------- + +TITLE: Solaris 10 Compilation Fix (SunOS) +DESCRIPTION: Resolves a critical issue where psutil failed to compile on Solaris 10. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_266 + +LANGUAGE: python +CODE: +``` +# Bug fix: [SunOS], [critical]: psutil does not compile on Solaris 10. +# This ensures psutil can be successfully compiled and used on Solaris 10. +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes - Process.cpu_affinity() Overflow +DESCRIPTION: Corrects a potential overflow issue with Process.cpu_affinity() on Linux systems that have more than 64 CPUs. This ensures accurate affinity reporting on high-core systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_423 + +LANGUAGE: python +CODE: +``` +# Fix for potential overflow in psutil.Process.cpu_affinity() on Linux with > 64 CPUs +# Original issue: https://github.com/giampaolo/psutil/issues/443 +``` + +---------------------------------------- + +TITLE: Py_DECREF Fix +DESCRIPTION: On Linux, a fix has been implemented for Py_DECREF calls on possible NULL objects, preventing potential crashes. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_356 + +LANGUAGE: c +CODE: +``` +Py_DECREF(obj); +``` + +---------------------------------------- + +TITLE: net_if_stats() OSError Fix (Linux) +DESCRIPTION: Resolves an issue on Linux where net_if_stats() could raise an OSError for specific network interface cards. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_292 + +LANGUAGE: python +CODE: +``` +from psutil import net_if_stats + +try: + stats = net_if_stats() + print(stats) +except OSError as e: + print(f"Error retrieving network interface stats: {e}") +``` + +---------------------------------------- + +TITLE: virtual_memory() TypeError Fix (NetBSD/Python 3) +DESCRIPTION: Corrects a TypeError that occurred in virtual_memory() on NetBSD when using Python 3. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_294 + +LANGUAGE: python +CODE: +``` +from psutil import virtual_memory + +try: + vmem = virtual_memory() + print(f"Memory Available: {vmem.available}") +except TypeError as e: + print(f"Caught TypeError: {e}") +``` + +---------------------------------------- + +TITLE: Process.cpu_affinity() NoSuchProcess Fix +DESCRIPTION: On Linux, Process.cpu_affinity() may no longer erroneously raise NoSuchProcess. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_343 + +LANGUAGE: python +CODE: +``` +process.cpu_affinity() +``` + +---------------------------------------- + +TITLE: Process.num_threads() Speedup (Linux/Python 3) +DESCRIPTION: Increases the speed of Process.num_threads() by 20% on Linux when using Python 3. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_290 + +LANGUAGE: python +CODE: +``` +from psutil import Process +import time + +p = Process() + +start_time = time.time() +num_threads = p.num_threads() +print(f"Number of threads: {num_threads}, Time taken: {time.time() - start_time:.6f}s") +``` + +---------------------------------------- + +TITLE: users() IP Address on Linux +DESCRIPTION: Bug fix for psutil version 6.1.1: Corrected the users() function on Linux to return the actual IP address of the logged-in user instead of 'localhost'. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_24 + +LANGUAGE: python +CODE: +``` +import psutil + +# Example usage +# for user in psutil.users(): +# print(f"Username: {user.name}, Host: {user.host}") +``` + +---------------------------------------- + +TITLE: disk_io_counters() Crash Fix on Old Linux +DESCRIPTION: Fixes a crash in disk_io_counters() on older Linux distributions (kernel < 2.6.5). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_393 + +LANGUAGE: python +CODE: +``` +# Original issue: disk_io_counters() may crash on old Linux distros (< 2.6.5). +# Fix implemented in psutil version 2.1.2 +``` + +---------------------------------------- + +TITLE: Process CPU Utilization +DESCRIPTION: Returns the process CPU utilization as a percentage. Can exceed 100% for multi-threaded processes. Non-blocking calls compare current times to the last call, with the first call returning 0.0. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_63 + +LANGUAGE: python +CODE: +``` +import psutil +p = psutil.Process() +# blocking +print(p.cpu_percent(interval=1)) +# non-blocking (percentage since last call) +print(p.cpu_percent(interval=None)) +``` + +---------------------------------------- + +TITLE: Windows Process Connections Intermittent Failure +DESCRIPTION: Addresses an intermittent failure in Process.connections() on Windows, which could occur with error code 0xC0000001. This improves the reliability of network connection information retrieval. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_190 + +LANGUAGE: python +CODE: +``` +# [Windows]: Process.connections() may sometimes fail with intermittent 0xC0000001. +``` + +---------------------------------------- + +TITLE: Process.memory_maps() Crash on RISCV64 Linux +DESCRIPTION: Bug fix for psutil version 7.0.1: Prevented Process.memory_maps() from crashing with IndexError on RISCV64 Linux due to malformed /proc/{PID}/smaps. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_13 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to internal implementation. +``` + +---------------------------------------- + +TITLE: Process.retcode Renamed to Process.returncode +DESCRIPTION: The `retcode` attribute of `Process` instances, particularly when returned by `wait_procs()`, has been renamed to `returncode`. This change aligns the naming convention with Python's standard `subprocess.Popen`. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_440 + +LANGUAGE: python +CODE: +``` +# When waiting for processes: +# results = psutil.wait_procs(processes) +# for p, ret_code in results: +# print(f"Process {p.pid} returned: {ret_code}") # ret_code is now returncode +``` + +---------------------------------------- + +TITLE: Compilation fix on SunOS +DESCRIPTION: Resolves a critical compilation error on SunOS 5.10. This ensures psutil can be successfully compiled on this version of SunOS. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_132 + +LANGUAGE: python +CODE: +``` +# Internal C code adjustment for SunOS 5.10 compatibility. +``` + +---------------------------------------- + +TITLE: macOS Process Threads Unit Correction +DESCRIPTION: Corrects an issue on macOS where Process.threads() incorrectly returned microseconds instead of seconds, ensuring accurate time reporting for thread durations. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_199 + +LANGUAGE: python +CODE: +``` +# [macOS]: Process.threads() incorrectly return microseconds instead of seconds. +``` + +---------------------------------------- + +TITLE: disk_partitions() OSError on SunOS +DESCRIPTION: Addresses an issue on SunOS where disk_partitions() could raise an OSError. This improves the reliability of retrieving disk partition information on this platform. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_117 + +LANGUAGE: python +CODE: +``` +psutil.disk_partitions() +# Now more robust on SunOS. +``` + +---------------------------------------- + +TITLE: wait_procs() Timeout Parameter +DESCRIPTION: Makes the 'timeout' parameter for wait_procs() optional, providing more flexibility in its usage. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_410 + +LANGUAGE: python +CODE: +``` +# Enhancement: wait_procs() "timeout" parameter is now optional. +# Implemented in psutil version 2.0.0 +``` + +---------------------------------------- + +TITLE: Windows Process Username Segfault Fix +DESCRIPTION: Addresses a critical bug on Windows where Process.username() could cause a segmentation fault (Python interpreter crash). This fix ensures the stability of retrieving process usernames. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_206 + +LANGUAGE: python +CODE: +``` +# [Windows], [critical]: Process.username() may cause a segfault (Python interpreter crash). +``` + +---------------------------------------- + +TITLE: Process Instance Caching in process_iter() +DESCRIPTION: process_iter() now caches Process instances between calls, improving performance by avoiding repeated object creation for the same process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_460 + +LANGUAGE: python +CODE: +``` +# Before: process_iter() created new Process objects on each call. +# After: process_iter() reuses cached Process objects. +``` + +---------------------------------------- + +TITLE: Linux /proc Read Buffer Size Increase +DESCRIPTION: Increases the read buffer size from 1KB to 32KB when reading lines from /proc pseudo files on Linux. This aims to improve the consistency of results obtained from process information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_58 + +LANGUAGE: python +CODE: +``` +# Conceptual: psutil internally adjusts buffer sizes for /proc reads on Linux. +# No direct user code change is typically needed for this enhancement. +``` + +---------------------------------------- + +TITLE: Speedup process_iter() on Windows +DESCRIPTION: Enhancement for psutil version 6.1.0: Significantly sped up process_iter() on Windows by using a faster method to determine process unique identity (process 'fast' create time). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_25 + +LANGUAGE: python +CODE: +``` +import psutil + +# Example usage +# for proc in psutil.process_iter(['pid', 'name']): +# print(f"PID: {proc.info['pid']}, Name: {proc.info['name']}") +``` + +---------------------------------------- + +TITLE: Compilation fix on SunOS +DESCRIPTION: Resolves a critical compilation error on SunOS 5.10. This ensures psutil can be successfully compiled on this version of SunOS. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_161 + +LANGUAGE: python +CODE: +``` +# Internal C code adjustment for SunOS 5.10 compatibility. +``` + +---------------------------------------- + +TITLE: psutil.phymem_usage() Accuracy Fix on Linux +DESCRIPTION: Corrects erroneous values reported by psutil.phymem_usage() on Linux, ensuring consistency with the 'free' command. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_472 + +LANGUAGE: python +CODE: +``` +# Fix for inaccurate physical memory usage reporting on Linux. +``` + +---------------------------------------- + +TITLE: Process.wait() Timeout Unit on Windows +DESCRIPTION: Corrects a bug on Windows where Process.wait() might raise TimeoutExpired with an incorrect timeout unit (milliseconds instead of seconds). + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_280 + +LANGUAGE: python +CODE: +``` +from psutil import Process, TimeoutExpired + +try: + p = Process() + # Example: wait for 5 seconds + p.wait(timeout=5) +except TimeoutExpired: + print("Process did not terminate within the specified timeout.") +except Exception as e: + print(f"An error occurred: {e}") +``` + +---------------------------------------- + +TITLE: Version Conflict Error Message +DESCRIPTION: Provides a better error message when a version conflict occurs during psutil import. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_309 + +LANGUAGE: python +CODE: +``` +# Example of how the error might be presented: +# try: +# import psutil +# except ImportError as e: +# print(f"Import error: {e}") +# # The error message should now be more informative about version conflicts. +``` + +---------------------------------------- + +TITLE: Process.cwd() AccessDenied for Cross-User Processes on Windows +DESCRIPTION: On Windows, Process.cwd() now raises AccessDenied instead of NoSuchProcess for processes owned by another user, providing more accurate error handling. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_464 + +LANGUAGE: python +CODE: +``` +try: + process.cwd() +except psutil.AccessDenied: + print('Access denied to process working directory.') +``` + +---------------------------------------- + +TITLE: Process Equality Check Fix +DESCRIPTION: Resolves an issue where a Process instance could unexpectedly raise NoSuchProcess when tested for equality with another object. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_482 + +LANGUAGE: python +CODE: +``` +# Fix for Process equality comparison raising NoSuchProcess. +``` + +---------------------------------------- + +TITLE: Avoid Segfault on Large Memory Processes +DESCRIPTION: Bug fix for psutil version 7.0.0: Avoided segfaults (cPython bug) on Process.memory_maps() for processes using hundreds of GBs of memory. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_20 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to internal implementation. +``` + +---------------------------------------- + +TITLE: psutil API Renames - Top Level Functions +DESCRIPTION: This section lists renamed top-level functions in the psutil library. While old names may still work, they are deprecated and will trigger a DeprecationWarning. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_420 + +LANGUAGE: APIDOC +CODE: +``` +Renamed psutil.* functions: + +Old name: psutil.get_pid_list() +Replacement: psutil.pids() + +Old name: psutil.get_users() +Replacement: psutil.users() + +Old name: psutil.get_boot_time() +Replacement: psutil.boot_time() +``` + +---------------------------------------- + +TITLE: Double free() and segfault vulnerability (CVE-2019-18874) +DESCRIPTION: Addresses a critical security vulnerability (CVE-2019-18874) where the use of Py_DECREF instead of Py_CLEAR could lead to a double free() and segfault. This fix ensures proper memory management in the C extensions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_121 + +LANGUAGE: python +CODE: +``` +# Internal C code adjustment for Python C API usage. +``` + +---------------------------------------- + +TITLE: Double free() and segfault vulnerability (CVE-2019-18874) +DESCRIPTION: Addresses a critical security vulnerability (CVE-2019-18874) where the use of Py_DECREF instead of Py_CLEAR could lead to a double free() and segfault. This fix ensures proper memory management in the C extensions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_150 + +LANGUAGE: python +CODE: +``` +# Internal C code adjustment for Python C API usage. +``` + +---------------------------------------- + +TITLE: Handling High PIDs in Process Class +DESCRIPTION: When the Process class is initialized with a PID that is excessively high, it will now raise a NoSuchProcess exception instead of an OverflowError. This provides a more specific and expected error for invalid PID values. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_39 + +LANGUAGE: python +CODE: +``` +try: + # Attempt to create a Process object with a very high PID + high_pid = 2**30 # Example of a very high PID + p = psutil.Process(high_pid) +except psutil.NoSuchProcess: + print(f"Error: Process with PID {high_pid} does not exist or is invalid.") +except OverflowError: + print(f"Error: PID {high_pid} is too large.") # This should no longer happen +``` + +---------------------------------------- + +TITLE: AIX Compilation Fix +DESCRIPTION: Addresses a critical compilation issue on AIX 7.1 where psutil would not compile due to a missing header file. This patch ensures compatibility with AIX systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_173 + +LANGUAGE: python +CODE: +``` +# [AIX], [critical]: psutil won't compile on AIX 7.1 due to missing header. +``` + +---------------------------------------- + +TITLE: IndexError on /proc/pid/stat Field Missing +DESCRIPTION: Bug fix for psutil version 6.1.0: Prevented IndexError when reading /proc/pid/stat on Linux if field 40 (blkio_ticks) is missing. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_31 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to internal implementation. +``` + +---------------------------------------- + +TITLE: CC compiler env var usage +DESCRIPTION: Ensures that the CC compiler environment variable is used if defined on Linux. This allows users to specify a preferred C compiler for building psutil. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_129 + +LANGUAGE: python +CODE: +``` +# Build process respects CC environment variable. +``` + +---------------------------------------- + +TITLE: CC compiler env var usage +DESCRIPTION: Ensures that the CC compiler environment variable is used if defined on Linux. This allows users to specify a preferred C compiler for building psutil. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_158 + +LANGUAGE: python +CODE: +``` +# Build process respects CC environment variable. +``` + +---------------------------------------- + +TITLE: Timeout Parameter Default Change +DESCRIPTION: The default value for the `timeout` parameter in `cpu_percent*` functions has been changed from `0.1` to `0.0`. This might affect the behavior of these functions if no explicit timeout is provided. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_438 + +LANGUAGE: python +CODE: +``` +# Example of cpu_percent with default timeout +# process.cpu_percent() # Default timeout is now 0.0 +``` + +---------------------------------------- + +TITLE: psutil Performance Improvement - Linux APIs +DESCRIPTION: Reports a significant performance improvement (approximately 30%) for most psutil APIs on Linux when using Python 3.x compared to previous versions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_433 + +LANGUAGE: python +CODE: +``` +# Performance improvement for most psutil APIs on Linux (Python 3.x) +# Original issue: https://github.com/giampaolo/psutil/issues/478 +``` + +---------------------------------------- + +TITLE: cpu_affinity() Compilation Error Fix +DESCRIPTION: Resolves a compilation error related to 'undefined symbol: CPU_ALLOC' on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_383 + +LANGUAGE: python +CODE: +``` +# Original issue: fix "undefined symbol: CPU_ALLOC" compilation error on Linux. +# Fix implemented in psutil version 2.1.3 +``` + +---------------------------------------- + +TITLE: Filter Processes by Memory Usage +DESCRIPTION: This code snippet filters processes that are consuming more than a specified amount of Resident Set Size (RSS) memory. It displays the process ID, name, and memory usage. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_99 + +LANGUAGE: python +CODE: +``` +import psutil +from pprint import pprint as pp + +pp([(p.pid, p.info['name'], p.info['memory_info'].rss) for p in psutil.process_iter(['name', 'memory_info']) if p.info['memory_info'].rss > 500 * 1024 * 1024]) +``` + +---------------------------------------- + +TITLE: UTF-8 Handling for Process Attributes +DESCRIPTION: On Python 3, psutil now correctly handles invalid UTF-8 data for process attributes like name(), cwd(), exe(), cmdline(), and open_files(). It uses the 'surrogateescape' error handler to replace corrupted data, preventing UnicodeDecodeError exceptions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_330 + +LANGUAGE: python +CODE: +``` +process.name() +``` + +LANGUAGE: python +CODE: +``` +process.cwd() +``` + +LANGUAGE: python +CODE: +``` +process.exe() +``` + +LANGUAGE: python +CODE: +``` +process.cmdline() +``` + +LANGUAGE: python +CODE: +``` +process.open_files() +``` + +---------------------------------------- + +TITLE: macOS cpu_freq() Apple M1 Fix +DESCRIPTION: Fixes an issue where cpu_freq() was broken on Apple M1 processors. This ensures CPU frequency reporting works correctly on M1 hardware. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_75 + +LANGUAGE: python +CODE: +``` +# Example of retrieving CPU frequency on macOS with Apple M1 +# import psutil +# freq = psutil.cpu_freq() +# if freq: +# print(f"CPU Frequency on M1: {freq.current} MHz") +``` + +---------------------------------------- + +TITLE: C Macro Removal (SunOS) +DESCRIPTION: Removes a C macro that is not available on newer Solaris versions, ensuring compatibility with updated SunOS systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_228 + +LANGUAGE: python +CODE: +``` +# Original issue: [SunOS]: remove C macro which will not be available on new Solaris versions. +# This change prevents compilation errors on newer Solaris releases. +``` + +---------------------------------------- + +TITLE: macOS Platform Constant Deprecation +DESCRIPTION: Deprecates the psutil.OSX constant in favor of the new psutil.MACOS constant for better clarity and consistency in identifying macOS platforms. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_195 + +LANGUAGE: python +CODE: +``` +# [macOS]: "psutil.OSX" constant is now deprecated in favor of new "psutil.MACOS". +``` + +---------------------------------------- + +TITLE: Process.memory_maps() TypeError Fix on Old Linux +DESCRIPTION: Fixes a TypeError that could occur in Process.memory_maps() on older Linux distributions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_395 + +LANGUAGE: python +CODE: +``` +# Original issue: Process.memory_maps() may raise TypeError on old Linux distros. +# Fix implemented in psutil version 2.1.2 +``` + +---------------------------------------- + +TITLE: VS 2013 Compilation Fix (Windows) +DESCRIPTION: Fixes a compilation error on Windows when using Visual Studio 2013. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_267 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Windows]: fix compilation error on VS 2013 (patch by Max Bélanger). +# This ensures compatibility with older Visual Studio versions for Windows builds. +``` + +---------------------------------------- + +TITLE: sensors_battery() power_plugged Lie Fix (Linux) +DESCRIPTION: Corrects instances where sensors_battery() 'power_plugged' status might be reported incorrectly on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_251 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Linux]: sensors_battery() 'power_plugged' may lie. +# This ensures the accuracy of the power plugged status. +``` + +---------------------------------------- + +TITLE: PSUTIL_DEBUG Mode Enhancement +DESCRIPTION: Enhances the PSUTIL_DEBUG mode to print the file name and line number of debug messages originating from C extension modules, aiding in debugging C-level issues. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_69 + +LANGUAGE: python +CODE: +``` +# To enable debug mode, set the environment variable PSUTIL_DEBUG=1 +# Example output when PSUTIL_DEBUG is enabled: +# DEBUG: /path/to/psutil/c_module.c:123 - Debug message here +``` + +---------------------------------------- + +TITLE: Thread Safety of cpu_percent() and cpu_times_percent() +DESCRIPTION: The cpu_percent() and cpu_times_percent() functions are now thread-safe. This means they can be called concurrently from multiple threads, with each call returning accurate and independent results, resolving a previous issue where concurrent calls could yield incorrect data. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_38 + +LANGUAGE: python +CODE: +``` +import threading + +def get_cpu_usage(): + # This call is now thread-safe + percent = psutil.cpu_percent(interval=None) + print(f"CPU Usage: {percent}%") + +# Example of calling from multiple threads +threads = [] +for _ in range(5): + t = threading.Thread(target=get_cpu_usage) + threads.append(t) + t.start() + +for t in threads: + t.join() +``` + +---------------------------------------- + +TITLE: psutil Deprecation - psutil.error module +DESCRIPTION: The long-deprecated 'psutil.error' module has been removed. Exception classes are now directly available under the 'psutil' namespace. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_434 + +LANGUAGE: python +CODE: +``` +# Removed deprecated psutil.error module +# Exception classes are now directly in the psutil namespace. +# Original issue: https://github.com/giampaolo/psutil/issues/479 +``` + +---------------------------------------- + +TITLE: AccessDenied for Process.children() on Linux +DESCRIPTION: Bug fix for psutil version 7.0.1: Process.children() on Linux now raises AccessDenied instead of PermissionError. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_7 + +LANGUAGE: python +CODE: +``` +from psutil import Process, AccessDenied + +# Example of catching AccessDenied +# try: +# children = process.children() +# except AccessDenied: +# print("Access denied to process children.") +``` + +---------------------------------------- + +TITLE: Python 2.6 Support Dropped +DESCRIPTION: This version drops support for Python 2.6, aligning the library with modern Python development practices and removing legacy compatibility code. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_56 + +LANGUAGE: python +CODE: +``` +# Code examples in this version are intended for Python 2.7+ or Python 3.x +# import sys +# if sys.version_info < (2, 7): +# print("This version of psutil requires Python 2.7 or higher.") +``` + +---------------------------------------- + +TITLE: Linux cpu_freq() GHz/MHz Unit Correction +DESCRIPTION: Corrects an issue on Linux where cpu_freq() erroneously reported the 'curr' value in GHz while 'min' and 'max' were in MHz. This ensures consistent units for CPU frequency. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_62 + +LANGUAGE: python +CODE: +``` +# Example of checking CPU frequency units on Linux +# import psutil +# freq = psutil.cpu_freq() +# if freq: +# print(f"Current: {freq.current}, Min: {freq.min}, Max: {freq.max}") +# # Note: The library now handles unit consistency internally. +``` + +---------------------------------------- + +TITLE: Suspend OSError Fix +DESCRIPTION: Fixes `Process.suspend()` to raise `AccessDenied` instead of `OSError`. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_528 + +LANGUAGE: python +CODE: +``` +p.suspend() +``` + +---------------------------------------- + +TITLE: Windows Process Connections MemoryError Fix +DESCRIPTION: Resolves an intermittent MemoryError that could occur with Process.connections() on Windows systems, improving the stability of network connection retrieval. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_201 + +LANGUAGE: python +CODE: +``` +# [Windows]: Process.connections() may sometime fail with MemoryError. +``` + +---------------------------------------- + +TITLE: Error Class Representation Improvement +DESCRIPTION: Improves the __repr__ and __str__ implementations for psutil error classes (e.g., NoSuchProcess, AccessDenied) for better formatting and readability. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_66 + +LANGUAGE: python +CODE: +``` +# Example of how psutil error messages are now formatted +# import psutil +# try: +# # Simulate an AccessDenied error +# raise psutil.AccessDenied(pid=1, name='some_process') +# except psutil.AccessDenied as e: +# print(repr(e)) +# print(str(e)) +``` + +---------------------------------------- + +TITLE: sensors_battery() Precision Fix (Linux) +DESCRIPTION: Improves the precision of the 'percent' field in sensors_battery() on Linux, making it a float. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_247 + +LANGUAGE: python +CODE: +``` +# Enhancement: [Linux]: sensors_battery() 'percent' is a float and is more precise. +# This provides more accurate battery level reporting. +``` + +---------------------------------------- + +TITLE: PSUTIL_HAVE_IOPRIO definition for older Linux kernels +DESCRIPTION: Resolves a compilation issue on Linux kernels older than 2.6.13 by ensuring PSUTIL_HAVE_IOPRIO is defined. This allows psutil to compile on a wider range of Linux systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_148 + +LANGUAGE: python +CODE: +``` +# Internal C code adjustment for kernel compatibility. +``` + +---------------------------------------- + +TITLE: Linux Process I/O Counters ValueError +DESCRIPTION: Fixes a potential ValueError that could be raised by Process.io_counters() on Linux systems, ensuring more robust operation. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_188 + +LANGUAGE: python +CODE: +``` +# [Linux]: Process.io_counters() may raise ValueError. +``` + +---------------------------------------- + +TITLE: POSIX Path/Name Truncation Fix +DESCRIPTION: Fixes truncated or erroneous values reported by `Process.name()` and `Process.exe()` properties on POSIX systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_531 + +LANGUAGE: python +CODE: +``` +p.name() +p.exe() +``` + +---------------------------------------- + +TITLE: FileNotFoundError in Process.cwd() on Linux +DESCRIPTION: Bug fix for psutil version 7.0.1: Resolved a race condition on Linux where Process.cwd() could fail with FileNotFoundError. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_5 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to internal implementation. +``` + +---------------------------------------- + +TITLE: Process.wait() POSIX Enum Return +DESCRIPTION: On POSIX systems, Process.wait() now returns an enum indicating the negative signal used to terminate the process. This provides more detailed information about process termination. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_95 + +LANGUAGE: APIDOC +CODE: +``` +Process.wait() + - On POSIX, returns an enum showing the negative signal which was used to terminate the process. + - Returns something like . +``` + +---------------------------------------- + +TITLE: Per-Process Threads Information +DESCRIPTION: Enables retrieval of information about threads belonging to a specific process, including memory leaks on macOS. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_494 + +LANGUAGE: python +CODE: +``` +p.threads() +``` + +---------------------------------------- + +TITLE: PSUTIL_HAVE_IOPRIO definition for older Linux kernels +DESCRIPTION: Resolves a compilation issue on Linux kernels older than 2.6.13 by ensuring PSUTIL_HAVE_IOPRIO is defined. This allows psutil to compile on a wider range of Linux systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_119 + +LANGUAGE: python +CODE: +``` +# Internal C code adjustment for kernel compatibility. +``` + +---------------------------------------- + +TITLE: Race Condition Fix in Process.stat() on Linux +DESCRIPTION: Bug fix for psutil version 6.1.1: Fixed a race condition on Linux where FileNotFoundError could occur if /proc/PID/stat did not exist but /proc/PID did. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_23 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to internal implementation. +``` + +---------------------------------------- + +TITLE: Process.name() Caching Fix +DESCRIPTION: On POSIX systems, Process.name() is no longer cached. This prevents potential issues where the process name might change and the cached value would be stale. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_329 + +LANGUAGE: python +CODE: +``` +process.name() +``` + +---------------------------------------- + +TITLE: cpu_freq() Segfault on ARM macOS +DESCRIPTION: Critical bug fix for psutil version 7.0.1: Fixed a segfault in cpu_freq() on ARM architectures on macOS. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_16 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to internal implementation. +``` + +---------------------------------------- + +TITLE: close() call on negative integers on OSX +DESCRIPTION: Prevents calling C's close() function on potentially negative integers on OSX. This avoids potential errors or crashes related to file descriptor handling. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_160 + +LANGUAGE: python +CODE: +``` +# Internal file descriptor handling improved for OSX. +``` + +---------------------------------------- + +TITLE: CPU Percent Erroneous Results (Non-blocking) +DESCRIPTION: Fixes erroneous results from `cpu_percent()` when used in non-blocking mode. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_539 + +LANGUAGE: python +CODE: +``` +psutil.cpu_percent(interval=None) +``` + +---------------------------------------- + +TITLE: Process.wait() CPU Hogging Fix +DESCRIPTION: Fixes Process.wait() from hogging CPU resources when called against a process that is not a child process. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_463 + +LANGUAGE: python +CODE: +``` +# Fix for Process.wait() CPU usage when not waiting for children. +``` + +---------------------------------------- + +TITLE: close() call on negative integers on OSX +DESCRIPTION: Prevents calling C's close() function on potentially negative integers on OSX. This avoids potential errors or crashes related to file descriptor handling. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_131 + +LANGUAGE: python +CODE: +``` +# Internal file descriptor handling improved for OSX. +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes - Namedtuples Pickling +DESCRIPTION: Ensures that namedtuples used within psutil are pickle-able, resolving issues when serializing psutil objects. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_426 + +LANGUAGE: python +CODE: +``` +# Fix for namedtuples not being pickle-able in psutil +# Original issue: https://github.com/giampaolo/psutil/issues/461 +``` + +---------------------------------------- + +TITLE: Linux Process.threads() NoSuchProcess Race Condition Fix +DESCRIPTION: Resolves a race condition in Process.threads() on Linux that could lead to a NoSuchProcess exception. This improves the stability of retrieving thread information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_50 + +LANGUAGE: python +CODE: +``` +# Example of handling potential NoSuchProcess exception for Process.threads() +# import psutil +# try: +# p = psutil.Process(pid) +# threads = p.threads() +# print(f"Number of threads: {len(threads)}") +# except psutil.NoSuchProcess: +# print(f"Process with PID {pid} no longer exists.") +# except Exception as e: +# print(f"An error occurred: {e}") +``` + +---------------------------------------- + +TITLE: disk_io_counters() ValueError on Linux +DESCRIPTION: Fixes a ValueError that could occur in disk_io_counters() on Linux systems lacking '/proc/diskstats'. This ensures the function handles systems without this file gracefully. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_118 + +LANGUAGE: python +CODE: +``` +psutil.disk_io_counters() +# Now handles systems without /proc/diskstats. +``` + +---------------------------------------- + +TITLE: disk_io_counters() ValueError on Linux +DESCRIPTION: Fixes a ValueError that could occur in disk_io_counters() on Linux systems lacking '/proc/diskstats'. This ensures the function handles systems without this file gracefully. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_147 + +LANGUAGE: python +CODE: +``` +psutil.disk_io_counters() +# Now handles systems without /proc/diskstats. +``` + +---------------------------------------- + +TITLE: macOS Disk Usage Report Fix +DESCRIPTION: Addresses inaccuracies in disk usage reporting on macOS 12 and later versions. This enhancement ensures more reliable disk space information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_49 + +LANGUAGE: python +CODE: +``` +# Conceptual example for checking disk usage on macOS +# import psutil +# try: +# disk_usage = psutil.disk_usage('/') +# print(f"Total: {disk_usage.total}, Used: {disk_usage.used}, Free: {disk_usage.free}") +# except Exception as e: +# print(f"Error getting disk usage: {e}") +``` + +---------------------------------------- + +TITLE: Python 2.7 Support Dropped +DESCRIPTION: Compatibility note for psutil version 7.0.0: Python 2.7 is no longer supported. The last version supporting Python 2.7 is psutil 6.1.X. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_18 + +LANGUAGE: bash +CODE: +``` +pip2 install psutil==6.1.* +``` + +---------------------------------------- + +TITLE: Process.memory_maps() Removal +DESCRIPTION: Removes the Process.memory_maps() method due to inherent issues causing segfaults. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_169 + +LANGUAGE: python +CODE: +``` +Process.memory_maps() +``` + +---------------------------------------- + +TITLE: macOS Virtual Memory Accuracy +DESCRIPTION: Corrects inaccuracies in available and used memory metrics reported by virtual_memory() on macOS, providing more precise system memory information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_189 + +LANGUAGE: python +CODE: +``` +# [OSX]: available and used memory (virtual_memory()) metrics are not accurate. +``` + +---------------------------------------- + +TITLE: Process.memory_maps() on macOS +DESCRIPTION: Addresses a critical bug on macOS where Process.memory_maps() could cause a segmentation fault. This fix ensures stability when accessing memory map information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_271 + +LANGUAGE: python +CODE: +``` +from psutil import Process + +try: + p = Process() + memory_maps = p.memory_maps() + # Process memory maps successfully +except Exception as e: + # Handle potential errors, though this specific bug is fixed + print(f"Error accessing memory maps: {e}") +``` + +---------------------------------------- + +TITLE: Linux Sensor Temperatures ValueError Fix +DESCRIPTION: Fixes a ValueError that could occur with sensors_temperatures() on Linux systems, ensuring more reliable temperature data retrieval. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_205 + +LANGUAGE: python +CODE: +``` +# [Linux]: sensors_temperatures() may fail with ValueError. +``` + +---------------------------------------- + +TITLE: psutil Bug Fixes - Process.children() and Process.ppid() Memory Leak +DESCRIPTION: Resolves a memory leak in Process.children() and Process.ppid() on Windows. This fix prevents gradual memory consumption by these methods. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_424 + +LANGUAGE: python +CODE: +``` +# Fix for memory leak in psutil.Process.children() and psutil.Process.ppid() on Windows +# Original issue: https://github.com/giampaolo/psutil/issues/448 +``` + +---------------------------------------- + +TITLE: Linux virtual_memory() ValueError in LCX Containers +DESCRIPTION: Fixes a ValueError that could occur in virtual_memory() when running psutil within LCX containers on Linux. This improves compatibility with containerized environments. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_63 + +LANGUAGE: python +CODE: +``` +# Example of retrieving virtual memory, potentially in a container +# import psutil +# try: +# mem = psutil.virtual_memory() +# print(f"Virtual Memory: {mem}") +# except ValueError as e: +# print(f"ValueError encountered, possibly in container: {e}") +``` + +---------------------------------------- + +TITLE: PID type handling +DESCRIPTION: Corrects the C type used when dealing with PIDs, ensuring it's either int or long as appropriate for the platform. Previously, 'long' was almost always assumed, which was incorrect on many systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_144 + +LANGUAGE: python +CODE: +``` +# Internal C code adjustment for PID handling. +``` + +---------------------------------------- + +TITLE: PID type handling +DESCRIPTION: Corrects the C type used when dealing with PIDs, ensuring it's either int or long as appropriate for the platform. Previously, 'long' was almost always assumed, which was incorrect on many systems. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_115 + +LANGUAGE: python +CODE: +``` +# Internal C code adjustment for PID handling. +``` + +---------------------------------------- + +TITLE: Linux sensors_battery() TypeError Fix +DESCRIPTION: Resolves a TypeError that could occur in sensors_battery() on PureOS Linux distributions. This ensures battery status can be retrieved reliably. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_79 + +LANGUAGE: python +CODE: +``` +# Example of retrieving battery status on Linux +# import psutil +# try: +# battery = psutil.sensors_battery() +# if battery: +# print(f"Battery percent: {battery.percent}%") +# except TypeError as e: +# print(f"TypeError encountered, possibly on PureOS: {e}") +# except Exception as e: +# print(f"Error retrieving battery status: {e}") +``` + +---------------------------------------- + +TITLE: disk_io_counters() TypeError Fix (Linux) +DESCRIPTION: Resolves a TypeError that occurs with disk_io_counters() on Linux with Python 3. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_245 + +LANGUAGE: python +CODE: +``` +# Bug fix: [Linux]: disk_io_counters() raises TypeError on Python 3. +# This ensures disk I/O statistics are correctly handled in Python 3. +``` + +---------------------------------------- + +TITLE: psutil Exception Pickling Fix +DESCRIPTION: Resolves an issue where psutil exception objects could not be pickled. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_261 + +LANGUAGE: python +CODE: +``` +# Bug fix: psutil exception objects could not be pickled. +# This allows psutil exceptions to be serialized and transmitted correctly. +``` + +---------------------------------------- + +TITLE: psutil.Popen wait() Exit Status Fix +DESCRIPTION: Corrects the behavior of psutil.Popen wait() to return the correct negative exit status when a process is terminated by a signal. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_262 + +LANGUAGE: python +CODE: +``` +# Bug fix: psutil.Popen wait() did not return the correct negative exit status if process is killed by a signal. +# This ensures accurate reporting of process exit statuses, especially when terminated by signals. +``` + +---------------------------------------- + +TITLE: Process Threads Count +DESCRIPTION: Returns the number of threads currently used by the process. This count is not cumulative. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/docs/index.rst#_snippet_58 + +LANGUAGE: python +CODE: +``` +import psutil + +p = psutil.Process() + +# Get number of threads +print(p.num_threads()) +``` + +---------------------------------------- + +TITLE: Negative Seconds Left in sensors_battery() on Linux +DESCRIPTION: Bug fix for psutil version 7.0.1: Corrected psutil.sensors_battery() to not report a negative amount for seconds left on Linux. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_14 + +LANGUAGE: python +CODE: +``` +import psutil + +# Example usage +# battery = psutil.sensors_battery() +# if battery and battery.secsleft >= 0: +# print(f"Seconds left: {battery.secsleft}") +``` + +---------------------------------------- + +TITLE: virtual_memory() Shared Memory Field (Linux) +DESCRIPTION: Adds a new 'shared' memory field to the return value of virtual_memory() on Linux, providing more detailed memory usage information. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_282 + +LANGUAGE: python +CODE: +``` +from psutil import virtual_memory + +vmem = virtual_memory() +print(f"Total: {vmem.total}, Available: {vmem.available}, Used: {vmem.used}, Shared: {vmem.shared}") +``` + +---------------------------------------- + +TITLE: Network Interface Address Name Change +DESCRIPTION: Renames the 'snic' field in the namedtuple returned by net_if_addrs() to 'snicaddr' for improved clarity and consistency. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_207 + +LANGUAGE: python +CODE: +``` +# net_if_addrs() namedtuple's name has been renamed from "snic" to "snicaddr". +``` + +---------------------------------------- + +TITLE: psutil.Popen __del__ Recursion Error +DESCRIPTION: Fixes a critical issue where psutil.Popen's __del__ method could cause a maximum recursion depth error. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_318 + +LANGUAGE: python +CODE: +``` +from psutil import Popen + +try: + # Example usage that might have triggered the error + p = Popen(['echo', 'hello']) + # The __del__ method should now be safe + del p +except RecursionError as e: + print(f"Caught RecursionError: {e}") +except Exception as e: + print(f"An error occurred: {e}") +``` + +---------------------------------------- + +TITLE: psutil.Popen __del__ Recursion Error Fix +DESCRIPTION: Resolves a critical bug where the __del__ method of psutil.Popen could lead to a maximum recursion depth error. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_307 + +LANGUAGE: python +CODE: +``` +from psutil import Popen + +try: + # Example usage that might have triggered the recursion error + p = Popen(['sleep', '5']) + # The __del__ method should now be safe + del p +except RecursionError as e: + print(f"Caught RecursionError: {e}") +except Exception as e: + print(f"An error occurred: {e}") +``` + +---------------------------------------- + +TITLE: macOS Debug Message Suppression +DESCRIPTION: Resolves an issue on macOS where psutil debug messages were erroneously printed at all times. These messages are now suppressed appropriately. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_193 + +LANGUAGE: python +CODE: +``` +# [OSX]: psutil debug messages are erroneously printed all the time. +``` + +---------------------------------------- + +TITLE: Process Threads Memory Leak (macOS) +DESCRIPTION: Fixes a memory leak issue on macOS related to `Process.threads()`. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_540 + +LANGUAGE: python +CODE: +``` +p.threads() +``` + +---------------------------------------- + +TITLE: psutil.Error AttributeError Fix +DESCRIPTION: Fixes an AttributeError that occurred when the psutil.Error class was raised manually and then passed through str(). This ensures proper string representation of exceptions. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_61 + +LANGUAGE: python +CODE: +``` +# Example demonstrating the fix for psutil.Error string representation +# import psutil +# try: +# raise psutil.Error("A custom error message") +# except psutil.Error as e: +# print(str(e)) # Should now work without AttributeError +``` + +---------------------------------------- + +TITLE: process_iter() Thread Safety +DESCRIPTION: The process_iter() function is now thread-safe, allowing it to be used concurrently from multiple threads without issues. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_336 + +LANGUAGE: python +CODE: +``` +psutil.process_iter() +``` + +---------------------------------------- + +TITLE: Segfault on Free-Threaded Python 3.13 +DESCRIPTION: Bug fix for psutil version 6.1.0: Resolved a segfault occurring on import in the free-threaded (no GIL) version of Python 3.13. + +SOURCE: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#_snippet_30 + +LANGUAGE: python +CODE: +``` +# Specific code fix details not provided, refers to internal implementation. +``` \ No newline at end of file diff --git a/examples/tmuxrunner_start.py b/examples/tmuxrunner_start.py new file mode 100755 index 0000000..77c8f48 --- /dev/null +++ b/examples/tmuxrunner_start.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +import sys + +from herolib.infra.tmuxrunner.task_runner_enhanced import TaskOrchestrator + +def main(): + tasks_dir = sys.argv[1] + api_port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000 + orchestrator = TaskOrchestrator(tasks_dir, api_port) + orchestrator.run() + + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("Usage: python enhanced_runner.py [api_port]") + sys.exit(1) + main() diff --git a/herolib.egg-info/PKG-INFO b/herolib.egg-info/PKG-INFO index 0c0ccad..7968f2d 100644 --- a/herolib.egg-info/PKG-INFO +++ b/herolib.egg-info/PKG-INFO @@ -6,6 +6,11 @@ Author-email: Kilo Code Requires-Python: >=3.12 Description-Content-Type: text/markdown Requires-Dist: peewee +Requires-Dist: psutil>=5.9.0 +Requires-Dist: fastapi>=0.100.0 +Requires-Dist: uvicorn>=0.23.0 +Requires-Dist: toml>=0.10.2 +Requires-Dist: libtmux>=0.25.0 # herolib_python diff --git a/herolib.egg-info/SOURCES.txt b/herolib.egg-info/SOURCES.txt index 77ae16c..a2f373a 100644 --- a/herolib.egg-info/SOURCES.txt +++ b/herolib.egg-info/SOURCES.txt @@ -64,6 +64,7 @@ herolib/downloader/scrape_scapegraph/scrape_md.py herolib/downloader/scrape_scapegraph/scrape_search.py herolib/downloader/scrape_scapegraph/scrape_with_local_llm.py herolib/downloader/scrape_scapegraph/scrape_with_local_llm_search.py +herolib/infra/tmuxrunner/enhanced_runner.py herolib/tools/__init__.py herolib/tools/extensions.py herolib/tools/gitscanner.py diff --git a/herolib.egg-info/requires.txt b/herolib.egg-info/requires.txt index 52b81ee..2edadb9 100644 --- a/herolib.egg-info/requires.txt +++ b/herolib.egg-info/requires.txt @@ -1 +1,6 @@ peewee +psutil>=5.9.0 +fastapi>=0.100.0 +uvicorn>=0.23.0 +toml>=0.10.2 +libtmux>=0.25.0 diff --git a/herolib/infra/tmuxrunner/instructions.md b/herolib/infra/tmuxrunner/instructions.md new file mode 100644 index 0000000..e69de29 diff --git a/herolib/infra/tmuxrunner/model.py b/herolib/infra/tmuxrunner/model.py new file mode 100644 index 0000000..48584dd --- /dev/null +++ b/herolib/infra/tmuxrunner/model.py @@ -0,0 +1,86 @@ +import os +import time +import re +import sys +import toml +import libtmux +from libtmux.pane import Pane +from libtmux.window import Window +from libtmux.session import Session +import psutil +from typing import Dict, List, Optional, Any, Set, Tuple +from dataclasses import dataclass, field, asdict +from datetime import datetime +import uuid +from pathlib import Path +import asyncio +import uvicorn +from fastapi import FastAPI, HTTPException +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel +import threading + +# Configuration +WAITING_MESSAGE = "WAITING FOR JOBS" +HPY_SH_PATH = "/root/heromonkey/functions/hpy.sh" # Path to hpy.sh + +@dataclass +class ProcessMetrics: + """Metrics for a running process and its children.""" + cpu_percent: float = 0.0 + memory_rss: int = 0 # Resident Set Size in bytes + memory_vms: int = 0 # Virtual Memory Size in bytes + memory_percent: float = 0.0 + num_threads: int = 0 + num_children: int = 0 + children_cpu_percent: float = 0.0 + children_memory_rss: int = 0 + last_updated: str = "" + +@dataclass +class TaskStatus: + """Status of an individual task (script).""" + script_path: str + script_name: str + state: str = "PENDING" # PENDING, WAITING, RUNNING, DONE, ERROR, CRASHED, TIMED_OUT + start_time: Optional[str] = None + end_time: Optional[str] = None + duration_seconds: float = 0.0 + exit_code: Optional[int] = None + error_message: Optional[str] = None + pane_id: Optional[str] = None + process_metrics: ProcessMetrics = field(default_factory=ProcessMetrics) + +@dataclass +class DirectoryStatus: + """Status of a directory containing tasks.""" + directory_num: int + directory_path: str + state: str = "PENDING" # PENDING, RUNNING, DONE, ERROR, TIMED_OUT + timeout: int = 600 + start_time: Optional[str] = None + end_time: Optional[str] = None + duration_seconds: float = 0.0 + tasks: List[TaskStatus] = field(default_factory=list) + window_name: Optional[str] = None + +@dataclass +class DAGStructure: + """Complete DAG structure for the task run.""" + run_name: str + run_id: str + state: str = "INITIALIZING" # INITIALIZING, RUNNING, COMPLETED, FAILED + start_time: str = "" + end_time: Optional[str] = None + duration_seconds: float = 0.0 + total_directories: int = 0 + completed_directories: int = 0 + failed_directories: int = 0 + directories: List[DirectoryStatus] = field(default_factory=list) + last_updated: str = "" + +class MetaData: + """Class to hold metadata for a task directory.""" + def __init__(self, timeout: int = 600): # Default timeout to 10 minutes (600 seconds) + self.timeout = timeout + # Add more attributes here in the future diff --git a/herolib/infra/tmuxrunner/process_monitor.py b/herolib/infra/tmuxrunner/process_monitor.py new file mode 100644 index 0000000..c88d9e1 --- /dev/null +++ b/herolib/infra/tmuxrunner/process_monitor.py @@ -0,0 +1,106 @@ +import os +import time +import re +import sys +import toml +import libtmux +from libtmux.pane import Pane +from libtmux.window import Window +from libtmux.session import Session +import psutil +from typing import Dict, List, Optional, Any, Set, Tuple +from dataclasses import dataclass, field, asdict +from datetime import datetime +import uuid +from pathlib import Path +import asyncio +import uvicorn +from fastapi import FastAPI, HTTPException +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel +import threading + + +class ProcessMonitor: + """Monitor processes running in tmux panes using psutil.""" + + @staticmethod + def get_pane_process_tree(pane: Pane) -> Tuple[Optional[psutil.Process], List[psutil.Process]]: + """Get the main process and all child processes for a tmux pane.""" + try: + pane_pid = pane.pane_pid + if pane_pid is None: + return None, [] + + # Get the main process + try: + main_process = psutil.Process(int(pane_pid)) + except (psutil.NoSuchProcess, ValueError): + return None, [] + + # Get all children recursively + children = [] + try: + children = main_process.children(recursive=True) + except psutil.NoSuchProcess: + pass + + return main_process, children + except Exception as e: + print(f"Error getting process tree: {e}") + return None, [] + + @staticmethod + def get_process_metrics(pane: Pane) -> ProcessMetrics: + """Get CPU and memory metrics for all processes in a pane.""" + metrics = ProcessMetrics() + metrics.last_updated = datetime.now().isoformat() + + main_proc, children = ProcessMonitor.get_pane_process_tree(pane) + + if main_proc is None: + return metrics + + try: + # Get main process metrics + if main_proc.is_running(): + metrics.cpu_percent = main_proc.cpu_percent(interval=0.1) + mem_info = main_proc.memory_info() + metrics.memory_rss = mem_info.rss + metrics.memory_vms = mem_info.vms + metrics.memory_percent = main_proc.memory_percent() + metrics.num_threads = main_proc.num_threads() + + # Get children metrics + metrics.num_children = len(children) + for child in children: + try: + if child.is_running(): + metrics.children_cpu_percent += child.cpu_percent(interval=0.1) + child_mem = child.memory_info() + metrics.children_memory_rss += child_mem.rss + except (psutil.NoSuchProcess, psutil.AccessDenied): + pass + + except (psutil.NoSuchProcess, psutil.AccessDenied) as e: + print(f"Error getting process metrics: {e}") + + return metrics + + @staticmethod + def is_process_running_command(pane: Pane, command_pattern: str) -> bool: + """Check if a specific command is running in the pane.""" + main_proc, children = ProcessMonitor.get_pane_process_tree(pane) + + all_processes = [main_proc] + children if main_proc else children + + for proc in all_processes: + try: + if proc and proc.is_running(): + cmdline = " ".join(proc.cmdline()) + if command_pattern in cmdline: + return True + except (psutil.NoSuchProcess, psutil.AccessDenied): + pass + + return False diff --git a/herolib/infra/tmuxrunner/task_runner.py b/herolib/infra/tmuxrunner/task_runner.py new file mode 100644 index 0000000..dd606f9 --- /dev/null +++ b/herolib/infra/tmuxrunner/task_runner.py @@ -0,0 +1,594 @@ +import os +import time +import re +import sys +import toml +import libtmux +from libtmux.pane import Pane +from libtmux.window import Window +from libtmux.session import Session +import psutil +from typing import Dict, List, Optional, Any, Set, Tuple +from dataclasses import dataclass, field, asdict +from datetime import datetime +import uuid +from pathlib import Path +import asyncio +import uvicorn +from fastapi import FastAPI, HTTPException +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel +import threading + +# Configuration +WAITING_MESSAGE = "WAITING FOR JOBS" +HPY_SH_PATH = "/root/heromonkey/functions/hpy.sh" # Path to hpy.sh + + +class TaskRunner: + def __init__(self, tasks_root_dir: str): + self.tasks_root_dir = tasks_root_dir + self.run_name = os.path.basename(os.path.abspath(tasks_root_dir)) # Derive run_name + self.session = self._get_current_tmux_session() + self.all_tasks_with_meta = self._get_sorted_tasks_with_meta(tasks_root_dir) + self.window_panes = {} # {window_idx: [pane1, pane2, ...]} + self.run_id = str(uuid.uuid4()) + self.dag = self._initialize_dag() + self.dag_file_path = Path(tasks_root_dir) / ".dag.toml" + self.process_monitor = ProcessMonitor() + self._save_dag() + + def _initialize_dag(self) -> DAGStructure: + """Initialize the DAG structure.""" + dag = DAGStructure( + run_name=self.run_name, + run_id=self.run_id, + state="INITIALIZING", + start_time=datetime.now().isoformat(), + total_directories=len(self.all_tasks_with_meta) + ) + + # Create directory entries + for dir_num, (scripts, metadata) in self.all_tasks_with_meta.items(): + dir_status = DirectoryStatus( + directory_num=dir_num, + directory_path=os.path.dirname(scripts[0]) if scripts else "", + timeout=metadata.timeout, + window_name=f"{self.run_name}_{dir_num}" + ) + + # Create task entries + for script_path in scripts: + task = TaskStatus( + script_path=script_path, + script_name=os.path.basename(script_path) + ) + dir_status.tasks.append(task) + + dag.directories.append(dir_status) + + return dag + + def _save_dag(self): + """Save the DAG structure to a TOML file.""" + try: + dag_dict = asdict(self.dag) + with open(self.dag_file_path, 'w') as f: + toml.dump(dag_dict, f) + except Exception as e: + print(f"Error saving DAG: {e}") + + def _update_task_state(self, dir_idx: int, task_idx: int, + state: str, error_message: Optional[str] = None): + """Update task state and save DAG.""" + task = self.dag.directories[dir_idx].tasks[task_idx] + old_state = task.state + task.state = state + + if state == "RUNNING" and old_state != "RUNNING": + task.start_time = datetime.now().isoformat() + elif state in ["DONE", "ERROR", "CRASHED", "TIMED_OUT"]: + task.end_time = datetime.now().isoformat() + if task.start_time: + start = datetime.fromisoformat(task.start_time) + end = datetime.fromisoformat(task.end_time) + task.duration_seconds = (end - start).total_seconds() + + if error_message: + task.error_message = error_message + + self.dag.last_updated = datetime.now().isoformat() + self._save_dag() + + def _update_directory_state(self, dir_idx: int, state: str): + """Update directory state and save DAG.""" + directory = self.dag.directories[dir_idx] + old_state = directory.state + directory.state = state + + if state == "RUNNING" and old_state != "RUNNING": + directory.start_time = datetime.now().isoformat() + elif state in ["DONE", "ERROR", "TIMED_OUT"]: + directory.end_time = datetime.now().isoformat() + if directory.start_time: + start = datetime.fromisoformat(directory.start_time) + end = datetime.fromisoformat(directory.end_time) + directory.duration_seconds = (end - start).total_seconds() + + if state == "DONE": + self.dag.completed_directories += 1 + else: + self.dag.failed_directories += 1 + + self._save_dag() + + def _check_task_status(self, script_path: str, pane: Pane) -> Tuple[str, Optional[str]]: + """ + Comprehensive task status checking. + Returns: (state, error_message) + """ + script_basename = os.path.basename(script_path) + done_file = f"{script_path}.done" + error_file = f"{script_path}.error" + ok_file = f"{script_path}.ok" + + # Check file markers + if os.path.exists(done_file) or os.path.exists(ok_file): + # Create .ok file if it doesn't exist + if not os.path.exists(ok_file): + Path(ok_file).touch() + return "DONE", None + + if os.path.exists(error_file): + error_msg = None + try: + with open(error_file, 'r') as f: + error_msg = f.read().strip() + except: + error_msg = "Unknown error" + return "ERROR", error_msg + + # Check if hpy command is running + if self.process_monitor.is_process_running_command(pane, f"hpy {script_basename}"): + return "RUNNING", None + + # Check if pane has any running process + if self._is_pane_running(pane): + # Might be setting up or running something else + return "RUNNING", None + + # If we get here, the process finished without markers + # This is likely a crash + error_msg = f"Process terminated without completion marker" + # Create error file + with open(error_file, 'w') as f: + f.write(error_msg) + return "CRASHED", error_msg + + def _monitor_directory_tasks(self, dir_idx: int, timeout: int) -> bool: + """ + Monitor tasks in a directory with comprehensive status checking. + Returns: True if all tasks completed successfully, False otherwise. + """ + directory = self.dag.directories[dir_idx] + scripts, metadata = self.all_tasks_with_meta[directory.directory_num] + panes = self.window_panes[dir_idx] + + self._update_directory_state(dir_idx, "RUNNING") + + start_time = time.time() + all_success = True + + while True: + all_finished = True + has_errors = False + + for task_idx, (script_path, pane) in enumerate(zip(scripts, panes)): + task = directory.tasks[task_idx] + + # Get process metrics if running + if task.state == "RUNNING": + metrics = self.process_monitor.get_process_metrics(pane) + task.process_metrics = metrics + + # Check task status + new_state, error_msg = self._check_task_status(script_path, pane) + + if new_state != task.state: + self._update_task_state(dir_idx, task_idx, new_state, error_msg) + print(f" Task {task.script_name}: {task.state}") + + if new_state == "RUNNING": + all_finished = False + elif new_state in ["ERROR", "CRASHED", "TIMED_OUT"]: + has_errors = True + all_success = False + + # Save DAG periodically + self._save_dag() + + if all_finished: + if has_errors: + self._update_directory_state(dir_idx, "ERROR") + else: + self._update_directory_state(dir_idx, "DONE") + break + + # Check timeout + elapsed = time.time() - start_time + if elapsed > timeout: + print(f" Directory {directory.directory_num} timed out!") + for task_idx, task in enumerate(directory.tasks): + if task.state == "RUNNING": + self._update_task_state(dir_idx, task_idx, "TIMED_OUT") + panes[task_idx].send_keys("C-c", literal=True) + self._update_directory_state(dir_idx, "TIMED_OUT") + all_success = False + break + + time.sleep(2) # Check every 2 seconds + + return all_success + + def run(self): + """Enhanced run method with DAG tracking.""" + print(f"Starting enhanced task orchestration for '{self.run_name}'") + print(f"Run ID: {self.run_id}") + print(f"DAG file: {self.dag_file_path}") + + self.dag.state = "RUNNING" + self._save_dag() + + # Initialize windows and panes (similar to original) + self._setup_windows_and_panes() + + # Process directories sequentially + overall_success = True + for dir_idx in range(len(self.dag.directories)): + directory = self.dag.directories[dir_idx] + print(f"\n--- Processing Directory {directory.directory_num} ---") + + # Start tasks if not the first directory + if dir_idx > 0: + self._start_directory_tasks(dir_idx) + + # Monitor tasks + success = self._monitor_directory_tasks( + dir_idx, + directory.timeout + ) + + if not success: + overall_success = False + + # Update final DAG state + self.dag.state = "COMPLETED" if overall_success else "FAILED" + self.dag.end_time = datetime.now().isoformat() + if self.dag.start_time: + start = datetime.fromisoformat(self.dag.start_time) + end = datetime.fromisoformat(self.dag.end_time) + self.dag.duration_seconds = (end - start).total_seconds() + self._save_dag() + + print(f"\nTask orchestration completed: {self.dag.state}") + print(f"Total duration: {self.dag.duration_seconds:.2f} seconds") + + def reset(self): + """Kills all processes and panes inside task windows, removes windows, and deletes .done/.error/.ok files.""" + print(f"\n--- Resetting run '{self.run_name}' ---") + self.cleanup() # First, kill all associated tmux windows + + # Then, remove all .done, .error, and .ok files + print(" Removing .done, .error, and .ok files...") + for dir_num, (scripts, metadata) in self.all_tasks_with_meta.items(): + for script_path in scripts: + done_file = f"{script_path}.done" + error_file = f"{script_path}.error" + ok_file = f"{script_path}.ok" + if os.path.exists(done_file): + os.remove(done_file) + print(f" Removed: {done_file}") + if os.path.exists(error_file): + os.remove(error_file) + print(f" Removed: {error_file}") + if os.path.exists(ok_file): + os.remove(ok_file) + print(f" Removed: {ok_file}") + + # Also remove the .dag.toml file if it exists + if hasattr(self, 'dag_file_path') and self.dag_file_path.exists(): + os.remove(self.dag_file_path) + print(f" Removed: {self.dag_file_path}") + print("Reset complete.") + + + + def _get_sorted_tasks_with_meta(self, tasks_root): + """ + Reads all scripts and .meta.toml from the tasks_root, sorts them by directory, + and then by script name within each directory. + Returns a dictionary where keys are directory numbers (e.g., 1, 2) + and values are tuples of (list_of_full_script_paths, MetaData_object). + """ + tasks_with_meta = {} + for dirpath, dirnames, filenames in os.walk(tasks_root): + if dirpath == tasks_root: + dirnames[:] = sorted([d for d in dirnames if d.isdigit()], key=int) + + relative_path = os.path.relpath(dirpath, tasks_root) + if relative_path != "." and relative_path.isdigit(): + dir_num = int(relative_path) + scripts = sorted([os.path.join(dirpath, f) for f in filenames if f.endswith(".sh")]) + + metadata_file = os.path.join(dirpath, ".meta.toml") + metadata = MetaData() # Default metadata + if os.path.exists(metadata_file): + try: + with open(metadata_file, 'r') as f: + meta_data_dict = toml.load(f) + if 'timeout' in meta_data_dict: + metadata.timeout = int(meta_data_dict['timeout']) + except Exception as e: + print(f"Warning: Could not read or parse .meta.toml for directory {dir_num}: {e}") + + if scripts: + tasks_with_meta[dir_num] = (scripts, metadata) + + sorted_tasks_with_meta = dict(sorted(tasks_with_meta.items())) + return sorted_tasks_with_meta + + def _get_current_tmux_session(self) -> Session: + """Gets the current tmux session based on TMUX environment variable.""" + server = libtmux.Server() + tmux_env = os.environ.get('TMUX') + + if not tmux_env: + raise Exception("Not running inside a tmux session. The 'TMUX' environment variable is not set.") + + try: + # TMUX variable format: /tmp/tmux-1000/default,12345,0 + # The last part '0' is the session index. + match = re.search(r',(\d+)$', tmux_env) + if not match: + raise Exception(f"Could not parse session index from TMUX environment variable: {tmux_env}") + + session_index_from_env = match.group(1) + + found_session = None + for s in server.sessions: + if s.session_id == f"${session_index_from_env}": + found_session = s + break + + if not found_session: + raise Exception(f"Could not find tmux session with ID: ${session_index_from_env}") + + print(f"Attached to current tmux session: '{found_session.name}' via TMUX env var.") + return found_session + except Exception as e: + raise Exception(f"Error getting current tmux session: {e}") + + def _create_tmux_window(self, window_name: str) -> Window: + """Creates a new tmux window.""" + window = self.session.new_window(attach=False, window_name=window_name) + print(f" Tmux window '{window_name}' created.") + return window + + def _create_tmux_pane(self, window: Window, pane_index: int, command: str) -> Pane: + """Creates a tmux pane and sends a command.""" + if pane_index == 0: + pane = window.active_pane + pane.send_keys("clear", enter=True) + else: + pane = window.split(attach=False) + + pane.send_keys(command, enter=True) + print(f" Pane {pane_index}: Command sent: '{command}'") + return pane + + def _is_pane_running(self, pane: Pane) -> bool: + """Checks if a tmux pane is still running a process.""" + try: + pane_pid = pane.pane_pid + if pane_pid is not None: + try: + pid_int = int(pane_pid) + if pid_int > 0: + os.kill(pid_int, 0) + return True + except (ValueError, OSError): + return False + return False + except Exception as e: + print(f"Error checking pane status for {pane.window_name}:{pane.pane_index}: {e}") + return False + + def _setup_windows_and_panes(self): + """Initial setup of tmux windows and panes for all tasks.""" + all_dir_nums = sorted(self.all_tasks_with_meta.keys()) + print("\n--- Initial Tmux Setup: Creating windows and panes ---") + for window_idx, dir_num in enumerate(all_dir_nums): + scripts, metadata = self.all_tasks_with_meta[dir_num] + window_name = f"{self.run_name}_{dir_num}" + window = self._create_tmux_window(window_name) + self.window_panes[window_idx] = [] + + for pane_idx, script_path in enumerate(scripts): + script_dir = os.path.dirname(script_path) + script_basename = os.path.basename(script_path) + + if window_idx == 0: + # Send cd command first, then the hpy command + pane = self._create_tmux_pane(window, pane_idx, f"cd {script_dir}") + pane.send_keys(f"source {HPY_SH_PATH} && hpy {script_basename}; echo \"Script {script_basename} finished.\"", enter=True) + print(f" Pane {pane_idx}: Command sent: 'cd {script_dir}' and 'source {HPY_SH_PATH} && hpy {script_basename}'") + else: + command = f"echo '{WAITING_MESSAGE} for {script_basename}'" + pane = self._create_tmux_pane(window, pane_idx, command) + self.window_panes[window_idx].append(pane) + + if window_idx == 0: + print(f" Window '{window_name}' (Directory {dir_num}) tasks started.") + else: + print(f" Window '{window_name}' (Directory {dir_num}) panes set to '{WAITING_MESSAGE}'.") + + def _start_directory_tasks(self, dir_idx: int): + """Starts tasks in a specific directory (window).""" + directory = self.dag.directories[dir_idx] + scripts, metadata = self.all_tasks_with_meta[directory.directory_num] + panes_in_current_window = self.window_panes[dir_idx] + + print(f"\n--- Activating tasks in window '{directory.window_name}' (Directory {directory.directory_num}) ---") + for pane_idx, script_path in enumerate(scripts): + script_dir = os.path.dirname(script_path) + script_basename = os.path.basename(script_path) + + pane = panes_in_current_window[pane_idx] + pane.send_keys("C-c", literal=True) # Clear any previous command/output + + # Send cd command first, then the hpy command + pane.send_keys(f"cd {script_dir}", enter=True) + pane.send_keys(f"source {HPY_SH_PATH} && hpy {script_basename}; echo \"Script {script_basename} finished.\"", enter=True) + print(f" Pane {pane_idx}: Command sent: 'cd {script_dir}' and 'source {HPY_SH_PATH} && hpy {script_basename}'") + + def run(self): + print(f"Starting task orchestration for run '{self.run_name}' from {self.tasks_root_dir}") + + if not self.all_tasks_with_meta: + print("No tasks found to execute.") + return + + print("Detected tasks:") + for dir_num, (scripts, metadata) in self.all_tasks_with_meta.items(): + print(f" Directory {dir_num} (Timeout: {metadata.timeout}s):") + for script in scripts: + print(f" - {script}") + + all_dir_nums = sorted(self.all_tasks_with_meta.keys()) + + # Phase 1: Initial setup - create all windows and panes, + # execute first window's tasks, set others to WAITING. + self._setup_windows_and_panes() + + # Phase 2: Sequential execution and monitoring + print("\n--- Starting Sequential Task Execution ---") + for window_idx, dir_num in enumerate(all_dir_nums): + scripts, metadata = self.all_tasks_with_meta[dir_num] + window_name = f"{self.run_name}_{dir_num}" + panes_in_current_window = self.window_panes[window_idx] + + if window_idx > 0: + self._start_directory_tasks(window_idx) + + print(f" Monitoring tasks in window '{window_name}' (Timeout: {metadata.timeout}s)...") + start_time = time.time() + script_states = {os.path.basename(s): "INITIAL" for s in scripts} # Track state for each script + + while True: + all_tasks_finished_or_failed = True + current_status_report = [] + + for pane_idx, script_path in enumerate(scripts): + script_basename = os.path.basename(script_path) + pane = panes_in_current_window[pane_idx] + done_file = f"{script_path}.done" + error_file = f"{script_path}.error" + ok_file = f"{script_path}.ok" # Added .ok file check + + current_script_state = script_states[script_basename] + new_script_state = current_script_state + + if os.path.exists(done_file) or os.path.exists(ok_file): # Check for .ok file + new_script_state = "DONE" + elif os.path.exists(error_file): + new_script_state = "ERROR" + elif self._is_pane_running(pane): + new_script_state = "RUNNING" + all_tasks_finished_or_failed = False + elif current_script_state == "RUNNING": + # If it was running but now isn't, and no done/error file, it crashed + new_script_state = "CRASHED" + + if new_script_state != current_script_state: + script_states[script_basename] = new_script_state + current_status_report.append(f" - {script_basename}: {new_script_state}") + + if current_status_report: + print(f" Status update for window '{window_name}' (Elapsed: {int(time.time() - start_time)}s):") + for report_line in current_status_report: + print(report_line) + + if all_tasks_finished_or_failed: + print(f" All tasks in window '{window_name}' completed or failed.") + break + + elapsed_time = time.time() - start_time + if elapsed_time > metadata.timeout: + print(f" ERROR: Tasks in window '{window_name}' timed out after {metadata.timeout}s.") + for pane_idx, script_path in enumerate(scripts): + script_basename = os.path.basename(script_path) + pane = panes_in_current_window[pane_idx] + if script_states[script_basename] == "RUNNING": + script_states[script_basename] = "TIMED_OUT" + print(f" - {script_basename}: TIMED_OUT (Killing pane)") + pane.send_keys("C-c", literal=True) + time.sleep(1) + break + + time.sleep(5) + + print("\nAll task directories processed. You can attach to the tmux session to review:") + print(f"tmux attach -t {self.session.name}") + + def cleanup(self): + """Removes all tmux windows created by this run.""" + print(f"\n--- Cleaning up tmux windows for run '{self.run_name}' ---") + print(f" Current session name: '{self.session.name}'") + all_session_windows = [w.name for w in self.session.windows if w.name] + print(f" All windows in current session: {all_session_windows}") + + windows_to_kill = [] + expected_prefix = f"{self.run_name}_" + print(f" Looking for windows starting with prefix: '{expected_prefix}'") + + for window in self.session.windows: + if window.name and window.name.startswith(expected_prefix): + windows_to_kill.append(window) + + if not windows_to_kill: + print(f" No windows found to kill with prefix '{expected_prefix}'.") + print("Cleanup complete.") + return + + print(f" Identified {len(windows_to_kill)} windows to kill: {[w.name for w in windows_to_kill]}") + for window in windows_to_kill: + try: + window.kill() + print(f" Killed window: '{window.name}'") + except Exception as e: + print(f" Error killing window '{window.name}': {e}") + print("Cleanup complete.") + + def reset(self): + """Kills all processes and panes inside task windows, removes windows, and deletes .done/.error files.""" + print(f"\n--- Resetting run '{self.run_name}' ---") + self.cleanup() # First, kill all associated tmux windows + + # Then, remove all .done and .error files + print(" Removing .done and .error files...") + for dir_num, (scripts, metadata) in self.all_tasks_with_meta.items(): + for script_path in scripts: + done_file = f"{script_path}.done" + error_file = f"{script_path}.error" + ok_file = f"{script_path}.ok" # Added .ok file to be removed + if os.path.exists(done_file): + os.remove(done_file) + print(f" Removed: {done_file}") + if os.path.exists(error_file): + os.remove(error_file) + print(f" Removed: {error_file}") + if os.path.exists(ok_file): # Remove .ok file + os.remove(ok_file) + print(f" Removed: {ok_file}") + print("Reset complete.") + diff --git a/herolib/infra/tmuxrunner/task_runner_api.py b/herolib/infra/tmuxrunner/task_runner_api.py new file mode 100644 index 0000000..abb2fd2 --- /dev/null +++ b/herolib/infra/tmuxrunner/task_runner_api.py @@ -0,0 +1,176 @@ +import os +import time +import re +import sys +import toml +import libtmux +from libtmux.pane import Pane +from libtmux.window import Window +from libtmux.session import Session +import psutil +from typing import Dict, List, Optional, Any, Set, Tuple +from dataclasses import dataclass, field, asdict +from datetime import datetime +import uuid +from pathlib import Path +import asyncio +import uvicorn +from fastapi import FastAPI, HTTPException +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel +import threading + + + +class TaskRunnerAPI: + """FastAPI interface for the task runner.""" + + def __init__(self, runner: EnhancedTaskRunner): + self.runner = runner + self.app = FastAPI(title="Task Runner API", version="1.0.0") + + # Add CORS middleware + self.app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + + self._setup_routes() + + def _setup_routes(self): + """Setup API routes.""" + + @self.app.get("/") + async def root(): + """Get API information.""" + return { + "name": "Task Runner API", + "version": "1.0.0", + "run_id": self.runner.run_id, + "run_name": self.runner.run_name + } + + @self.app.get("/status") + async def get_status(): + """Get current run status.""" + return { + "run_id": self.runner.run_id, + "run_name": self.runner.run_name, + "state": self.runner.dag.state, + "start_time": self.runner.dag.start_time, + "end_time": self.runner.dag.end_time, + "duration_seconds": self.runner.dag.duration_seconds, + "total_directories": self.runner.dag.total_directories, + "completed_directories": self.runner.dag.completed_directories, + "failed_directories": self.runner.dag.failed_directories + } + + @self.app.get("/directories") + async def get_directories(): + """Get all directory statuses.""" + return [ + { + "directory_num": d.directory_num, + "directory_path": d.directory_path, + "state": d.state, + "timeout": d.timeout, + "start_time": d.start_time, + "end_time": d.end_time, + "duration_seconds": d.duration_seconds, + "task_count": len(d.tasks), + "tasks_done": sum(1 for t in d.tasks if t.state == "DONE"), + "tasks_error": sum(1 for t in d.tasks if t.state in ["ERROR", "CRASHED", "TIMED_OUT"]) + } + for d in self.runner.dag.directories + ] + + @self.app.get("/directories/{dir_num}/tasks") + async def get_directory_tasks(dir_num: int): + """Get tasks for a specific directory.""" + for d in self.runner.dag.directories: + if d.directory_num == dir_num: + return d.tasks + raise HTTPException(status_code=404, detail="Directory not found") + + @self.app.get("/tasks/{dir_num}/{task_name}") + async def get_task_details(dir_num: int, task_name: str): + """Get detailed information about a specific task.""" + for d in self.runner.dag.directories: + if d.directory_num == dir_num: + for t in d.tasks: + if t.script_name == task_name: + return t + raise HTTPException(status_code=404, detail="Task not found") + + @self.app.get("/metrics") + async def get_metrics(): + """Get current process metrics for all running tasks.""" + metrics = [] + for d in self.runner.dag.directories: + for t in d.tasks: + if t.state == "RUNNING": + metrics.append({ + "directory": d.directory_num, + "task": t.script_name, + "cpu_percent": t.process_metrics.cpu_percent, + "memory_rss_mb": t.process_metrics.memory_rss / (1024 * 1024), + "memory_percent": t.process_metrics.memory_percent, + "num_threads": t.process_metrics.num_threads, + "num_children": t.process_metrics.num_children + }) + return metrics + + @self.app.get("/dag") + async def get_full_dag(): + """Get the complete DAG structure.""" + return asdict(self.runner.dag) + + def start(self, host: str = "0.0.0.0", port: int = 8000): + """Start the FastAPI server.""" + uvicorn.run(self.app, host=host, port=port) + +class TaskOrchestrator: + """Main orchestrator that runs tasks and API server.""" + + def __init__(self, tasks_dir: str, api_port: int = 8000): + self.runner = EnhancedTaskRunner(tasks_dir) + self.api = TaskRunnerAPI(self.runner) + self.api_thread = None + + def start_api_server(self, port: int = 8000): + """Start API server in a separate thread.""" + self.api_thread = threading.Thread( + target=self.api.start, + args=("0.0.0.0", port), + daemon=True + ) + self.api_thread.start() + print(f"API server started on http://0.0.0.0:{port}") + + def run(self): + """Run the task orchestration.""" + # Start API server + self.start_api_server() + + # Reset and run tasks + self.runner.reset() + try: + self.runner.run() + except Exception as e: + print(f"Error during execution: {e}") + self.runner.dag.state = "FAILED" + self.runner.dag.end_time = datetime.now().isoformat() + self.runner._save_dag() + + print("\nExecution completed. API server still running.") + print("Press Ctrl+C to stop the API server.") + + try: + # Keep the main thread alive for API access + while True: + time.sleep(1) + except KeyboardInterrupt: + print("\nShutting down...") diff --git a/install.sh b/install.sh index 33d5f1b..fc83c39 100755 --- a/install.sh +++ b/install.sh @@ -48,12 +48,3 @@ else uv pip install herolib@git+https://git.ourworld.tf/herocode/herolib_python.git --force-reinstall --no-cache-dir fi echo -e "${GREEN}✅ Dependencies installed${NC}" - -# Create necessary directories -mkdir -p static/css static/js static/images -mkdir -p templates -mkdir -p md - -echo -e "${GREEN}✅ Directory structure verified${NC}" - -echo -e "${GREEN}🎉 Installation complete! You can now run start_server.sh${NC}" \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index cae9c9b..3e2c062 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,7 +7,7 @@ authors = [ ] readme = "README.md" requires-python = ">=3.12" -dependencies = ["peewee"] +dependencies = ["peewee", "psutil>=5.9.0", "fastapi>=0.100.0", "uvicorn>=0.23.0", "toml>=0.10.2", "libtmux>=0.25.0"] [build-system] @@ -18,4 +18,4 @@ build-backend = "setuptools.build_meta" [tool.setuptools.packages.find] where = ["."] -include = ["herolib*"] \ No newline at end of file +include = ["herolib*"] diff --git a/uv.lock b/uv.lock index f6863dc..f5f5694 100644 --- a/uv.lock +++ b/uv.lock @@ -1,20 +1,254 @@ version = 1 revision = 3 -requires-python = "==3.12" +requires-python = ">=3.12" + +[[package]] +name = "annotated-types" +version = "0.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ee/67/531ea369ba64dcff5ec9c3402f9f51bf748cec26dde048a2f973a4eea7f5/annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89", size = 16081, upload-time = "2024-05-20T21:33:25.928Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643, upload-time = "2024-05-20T21:33:24.1Z" }, +] + +[[package]] +name = "anyio" +version = "4.10.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "sniffio" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f1/b4/636b3b65173d3ce9a38ef5f0522789614e590dab6a8d505340a4efe4c567/anyio-4.10.0.tar.gz", hash = "sha256:3f3fae35c96039744587aa5b8371e7e8e603c0702999535961dd336026973ba6", size = 213252, upload-time = "2025-08-04T08:54:26.451Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6f/12/e5e0282d673bb9746bacfb6e2dba8719989d3660cdb2ea79aee9a9651afb/anyio-4.10.0-py3-none-any.whl", hash = "sha256:60e474ac86736bbfd6f210f7a61218939c318f43f9972497381f1c5e930ed3d1", size = 107213, upload-time = "2025-08-04T08:54:24.882Z" }, +] + +[[package]] +name = "click" +version = "8.2.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/60/6c/8ca2efa64cf75a977a0d7fac081354553ebe483345c734fb6b6515d96bbc/click-8.2.1.tar.gz", hash = "sha256:27c491cc05d968d271d5a1db13e3b5a184636d9d930f148c50b038f0d0646202", size = 286342, upload-time = "2025-05-20T23:19:49.832Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/85/32/10bb5764d90a8eee674e9dc6f4db6a0ab47c8c4d0d83c27f7c39ac415a4d/click-8.2.1-py3-none-any.whl", hash = "sha256:61a3265b914e850b85317d0b3109c7f8cd35a670f963866005d6ef1d5175a12b", size = 102215, upload-time = "2025-05-20T23:19:47.796Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "fastapi" +version = "0.116.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, + { name = "starlette" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/78/d7/6c8b3bfe33eeffa208183ec037fee0cce9f7f024089ab1c5d12ef04bd27c/fastapi-0.116.1.tar.gz", hash = "sha256:ed52cbf946abfd70c5a0dccb24673f0670deeb517a88b3544d03c2a6bf283143", size = 296485, upload-time = "2025-07-11T16:22:32.057Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e5/47/d63c60f59a59467fda0f93f46335c9d18526d7071f025cb5b89d5353ea42/fastapi-0.116.1-py3-none-any.whl", hash = "sha256:c46ac7c312df840f0c9e220f7964bada936781bc4e2e6eb71f1c4d7553786565", size = 95631, upload-time = "2025-07-11T16:22:30.485Z" }, +] + +[[package]] +name = "h11" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, +] [[package]] name = "herolib" version = "0.1.0" source = { editable = "." } dependencies = [ + { name = "fastapi" }, + { name = "libtmux" }, { name = "peewee" }, + { name = "psutil" }, + { name = "toml" }, + { name = "uvicorn" }, ] [package.metadata] -requires-dist = [{ name = "peewee" }] +requires-dist = [ + { name = "fastapi", specifier = ">=0.100.0" }, + { name = "libtmux", specifier = ">=0.25.0" }, + { name = "peewee" }, + { name = "psutil", specifier = ">=5.9.0" }, + { name = "toml", specifier = ">=0.10.2" }, + { name = "uvicorn", specifier = ">=0.23.0" }, +] + +[[package]] +name = "idna" +version = "3.10" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f1/70/7703c29685631f5a7590aa73f1f1d3fa9a380e654b86af429e0934a32f7d/idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9", size = 190490, upload-time = "2024-09-15T18:07:39.745Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3", size = 70442, upload-time = "2024-09-15T18:07:37.964Z" }, +] + +[[package]] +name = "libtmux" +version = "0.46.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9c/aa/7e1dcaa097156d6f3a7d8669be4389dced997feeb81744e3ff4681d65ee8/libtmux-0.46.2.tar.gz", hash = "sha256:9a398fec5d714129c8344555d466e1a903dfc0f741ba07aabe75a8ceb25c5dda", size = 346887, upload-time = "2025-05-26T19:40:04.096Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d6/2f/9d207039fcfa00d3b30e4d765f062fbcc42c873c7518a8cfebb3eafd00e0/libtmux-0.46.2-py3-none-any.whl", hash = "sha256:6c32dbf22bde8e5e33b2714a4295f6e838dc640f337cd4c085a044f6828c7793", size = 60873, upload-time = "2025-05-26T19:40:02.284Z" }, +] [[package]] name = "peewee" version = "3.18.2" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/04/89/76f6f1b744c8608e0d416b588b9d63c2a500ff800065ae610f7c80f532d6/peewee-3.18.2.tar.gz", hash = "sha256:77a54263eb61aff2ea72f63d2eeb91b140c25c1884148e28e4c0f7c4f64996a0", size = 949220, upload-time = "2025-07-08T12:52:03.941Z" } + +[[package]] +name = "psutil" +version = "7.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2a/80/336820c1ad9286a4ded7e845b2eccfcb27851ab8ac6abece774a6ff4d3de/psutil-7.0.0.tar.gz", hash = "sha256:7be9c3eba38beccb6495ea33afd982a44074b78f28c434a1f51cc07fd315c456", size = 497003, upload-time = "2025-02-13T21:54:07.946Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ed/e6/2d26234410f8b8abdbf891c9da62bee396583f713fb9f3325a4760875d22/psutil-7.0.0-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:101d71dc322e3cffd7cea0650b09b3d08b8e7c4109dd6809fe452dfd00e58b25", size = 238051, upload-time = "2025-02-13T21:54:12.36Z" }, + { url = "https://files.pythonhosted.org/packages/04/8b/30f930733afe425e3cbfc0e1468a30a18942350c1a8816acfade80c005c4/psutil-7.0.0-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:39db632f6bb862eeccf56660871433e111b6ea58f2caea825571951d4b6aa3da", size = 239535, upload-time = "2025-02-13T21:54:16.07Z" }, + { url = "https://files.pythonhosted.org/packages/2a/ed/d362e84620dd22876b55389248e522338ed1bf134a5edd3b8231d7207f6d/psutil-7.0.0-cp36-abi3-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1fcee592b4c6f146991ca55919ea3d1f8926497a713ed7faaf8225e174581e91", size = 275004, upload-time = "2025-02-13T21:54:18.662Z" }, + { url = "https://files.pythonhosted.org/packages/bf/b9/b0eb3f3cbcb734d930fdf839431606844a825b23eaf9a6ab371edac8162c/psutil-7.0.0-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4b1388a4f6875d7e2aff5c4ca1cc16c545ed41dd8bb596cefea80111db353a34", size = 277986, upload-time = "2025-02-13T21:54:21.811Z" }, + { url = "https://files.pythonhosted.org/packages/eb/a2/709e0fe2f093556c17fbafda93ac032257242cabcc7ff3369e2cb76a97aa/psutil-7.0.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a5f098451abc2828f7dc6b58d44b532b22f2088f4999a937557b603ce72b1993", size = 279544, upload-time = "2025-02-13T21:54:24.68Z" }, + { url = "https://files.pythonhosted.org/packages/50/e6/eecf58810b9d12e6427369784efe814a1eec0f492084ce8eb8f4d89d6d61/psutil-7.0.0-cp37-abi3-win32.whl", hash = "sha256:ba3fcef7523064a6c9da440fc4d6bd07da93ac726b5733c29027d7dc95b39d99", size = 241053, upload-time = "2025-02-13T21:54:34.31Z" }, + { url = "https://files.pythonhosted.org/packages/50/1b/6921afe68c74868b4c9fa424dad3be35b095e16687989ebbb50ce4fceb7c/psutil-7.0.0-cp37-abi3-win_amd64.whl", hash = "sha256:4cf3d4eb1aa9b348dec30105c55cd9b7d4629285735a102beb4441e38db90553", size = 244885, upload-time = "2025-02-13T21:54:37.486Z" }, +] + +[[package]] +name = "pydantic" +version = "2.11.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/00/dd/4325abf92c39ba8623b5af936ddb36ffcfe0beae70405d456ab1fb2f5b8c/pydantic-2.11.7.tar.gz", hash = "sha256:d989c3c6cb79469287b1569f7447a17848c998458d49ebe294e975b9baf0f0db", size = 788350, upload-time = "2025-06-14T08:33:17.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6a/c0/ec2b1c8712ca690e5d61979dee872603e92b8a32f94cc1b72d53beab008a/pydantic-2.11.7-py3-none-any.whl", hash = "sha256:dde5df002701f6de26248661f6835bbe296a47bf73990135c7d07ce741b9623b", size = 444782, upload-time = "2025-06-14T08:33:14.905Z" }, +] + +[[package]] +name = "pydantic-core" +version = "2.33.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ad/88/5f2260bdfae97aabf98f1778d43f69574390ad787afb646292a638c923d4/pydantic_core-2.33.2.tar.gz", hash = "sha256:7cb8bc3605c29176e1b105350d2e6474142d7c1bd1d9327c4a9bdb46bf827acc", size = 435195, upload-time = "2025-04-23T18:33:52.104Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/8a/2b41c97f554ec8c71f2a8a5f85cb56a8b0956addfe8b0efb5b3d77e8bdc3/pydantic_core-2.33.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a7ec89dc587667f22b6a0b6579c249fca9026ce7c333fc142ba42411fa243cdc", size = 2009000, upload-time = "2025-04-23T18:31:25.863Z" }, + { url = "https://files.pythonhosted.org/packages/a1/02/6224312aacb3c8ecbaa959897af57181fb6cf3a3d7917fd44d0f2917e6f2/pydantic_core-2.33.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3c6db6e52c6d70aa0d00d45cdb9b40f0433b96380071ea80b09277dba021ddf7", size = 1847996, upload-time = "2025-04-23T18:31:27.341Z" }, + { url = "https://files.pythonhosted.org/packages/d6/46/6dcdf084a523dbe0a0be59d054734b86a981726f221f4562aed313dbcb49/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e61206137cbc65e6d5256e1166f88331d3b6238e082d9f74613b9b765fb9025", size = 1880957, upload-time = "2025-04-23T18:31:28.956Z" }, + { url = "https://files.pythonhosted.org/packages/ec/6b/1ec2c03837ac00886ba8160ce041ce4e325b41d06a034adbef11339ae422/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:eb8c529b2819c37140eb51b914153063d27ed88e3bdc31b71198a198e921e011", size = 1964199, upload-time = "2025-04-23T18:31:31.025Z" }, + { url = "https://files.pythonhosted.org/packages/2d/1d/6bf34d6adb9debd9136bd197ca72642203ce9aaaa85cfcbfcf20f9696e83/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c52b02ad8b4e2cf14ca7b3d918f3eb0ee91e63b3167c32591e57c4317e134f8f", size = 2120296, upload-time = "2025-04-23T18:31:32.514Z" }, + { url = "https://files.pythonhosted.org/packages/e0/94/2bd0aaf5a591e974b32a9f7123f16637776c304471a0ab33cf263cf5591a/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:96081f1605125ba0855dfda83f6f3df5ec90c61195421ba72223de35ccfb2f88", size = 2676109, upload-time = "2025-04-23T18:31:33.958Z" }, + { url = "https://files.pythonhosted.org/packages/f9/41/4b043778cf9c4285d59742281a769eac371b9e47e35f98ad321349cc5d61/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8f57a69461af2a5fa6e6bbd7a5f60d3b7e6cebb687f55106933188e79ad155c1", size = 2002028, upload-time = "2025-04-23T18:31:39.095Z" }, + { url = "https://files.pythonhosted.org/packages/cb/d5/7bb781bf2748ce3d03af04d5c969fa1308880e1dca35a9bd94e1a96a922e/pydantic_core-2.33.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:572c7e6c8bb4774d2ac88929e3d1f12bc45714ae5ee6d9a788a9fb35e60bb04b", size = 2100044, upload-time = "2025-04-23T18:31:41.034Z" }, + { url = "https://files.pythonhosted.org/packages/fe/36/def5e53e1eb0ad896785702a5bbfd25eed546cdcf4087ad285021a90ed53/pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:db4b41f9bd95fbe5acd76d89920336ba96f03e149097365afe1cb092fceb89a1", size = 2058881, upload-time = "2025-04-23T18:31:42.757Z" }, + { url = "https://files.pythonhosted.org/packages/01/6c/57f8d70b2ee57fc3dc8b9610315949837fa8c11d86927b9bb044f8705419/pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:fa854f5cf7e33842a892e5c73f45327760bc7bc516339fda888c75ae60edaeb6", size = 2227034, upload-time = "2025-04-23T18:31:44.304Z" }, + { url = "https://files.pythonhosted.org/packages/27/b9/9c17f0396a82b3d5cbea4c24d742083422639e7bb1d5bf600e12cb176a13/pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:5f483cfb75ff703095c59e365360cb73e00185e01aaea067cd19acffd2ab20ea", size = 2234187, upload-time = "2025-04-23T18:31:45.891Z" }, + { url = "https://files.pythonhosted.org/packages/b0/6a/adf5734ffd52bf86d865093ad70b2ce543415e0e356f6cacabbc0d9ad910/pydantic_core-2.33.2-cp312-cp312-win32.whl", hash = "sha256:9cb1da0f5a471435a7bc7e439b8a728e8b61e59784b2af70d7c169f8dd8ae290", size = 1892628, upload-time = "2025-04-23T18:31:47.819Z" }, + { url = "https://files.pythonhosted.org/packages/43/e4/5479fecb3606c1368d496a825d8411e126133c41224c1e7238be58b87d7e/pydantic_core-2.33.2-cp312-cp312-win_amd64.whl", hash = "sha256:f941635f2a3d96b2973e867144fde513665c87f13fe0e193c158ac51bfaaa7b2", size = 1955866, upload-time = "2025-04-23T18:31:49.635Z" }, + { url = "https://files.pythonhosted.org/packages/0d/24/8b11e8b3e2be9dd82df4b11408a67c61bb4dc4f8e11b5b0fc888b38118b5/pydantic_core-2.33.2-cp312-cp312-win_arm64.whl", hash = "sha256:cca3868ddfaccfbc4bfb1d608e2ccaaebe0ae628e1416aeb9c4d88c001bb45ab", size = 1888894, upload-time = "2025-04-23T18:31:51.609Z" }, + { url = "https://files.pythonhosted.org/packages/46/8c/99040727b41f56616573a28771b1bfa08a3d3fe74d3d513f01251f79f172/pydantic_core-2.33.2-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:1082dd3e2d7109ad8b7da48e1d4710c8d06c253cbc4a27c1cff4fbcaa97a9e3f", size = 2015688, upload-time = "2025-04-23T18:31:53.175Z" }, + { url = "https://files.pythonhosted.org/packages/3a/cc/5999d1eb705a6cefc31f0b4a90e9f7fc400539b1a1030529700cc1b51838/pydantic_core-2.33.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f517ca031dfc037a9c07e748cefd8d96235088b83b4f4ba8939105d20fa1dcd6", size = 1844808, upload-time = "2025-04-23T18:31:54.79Z" }, + { url = "https://files.pythonhosted.org/packages/6f/5e/a0a7b8885c98889a18b6e376f344da1ef323d270b44edf8174d6bce4d622/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a9f2c9dd19656823cb8250b0724ee9c60a82f3cdf68a080979d13092a3b0fef", size = 1885580, upload-time = "2025-04-23T18:31:57.393Z" }, + { url = "https://files.pythonhosted.org/packages/3b/2a/953581f343c7d11a304581156618c3f592435523dd9d79865903272c256a/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:2b0a451c263b01acebe51895bfb0e1cc842a5c666efe06cdf13846c7418caa9a", size = 1973859, upload-time = "2025-04-23T18:31:59.065Z" }, + { url = "https://files.pythonhosted.org/packages/e6/55/f1a813904771c03a3f97f676c62cca0c0a4138654107c1b61f19c644868b/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1ea40a64d23faa25e62a70ad163571c0b342b8bf66d5fa612ac0dec4f069d916", size = 2120810, upload-time = "2025-04-23T18:32:00.78Z" }, + { url = "https://files.pythonhosted.org/packages/aa/c3/053389835a996e18853ba107a63caae0b9deb4a276c6b472931ea9ae6e48/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0fb2d542b4d66f9470e8065c5469ec676978d625a8b7a363f07d9a501a9cb36a", size = 2676498, upload-time = "2025-04-23T18:32:02.418Z" }, + { url = "https://files.pythonhosted.org/packages/eb/3c/f4abd740877a35abade05e437245b192f9d0ffb48bbbbd708df33d3cda37/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9fdac5d6ffa1b5a83bca06ffe7583f5576555e6c8b3a91fbd25ea7780f825f7d", size = 2000611, upload-time = "2025-04-23T18:32:04.152Z" }, + { url = "https://files.pythonhosted.org/packages/59/a7/63ef2fed1837d1121a894d0ce88439fe3e3b3e48c7543b2a4479eb99c2bd/pydantic_core-2.33.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:04a1a413977ab517154eebb2d326da71638271477d6ad87a769102f7c2488c56", size = 2107924, upload-time = "2025-04-23T18:32:06.129Z" }, + { url = "https://files.pythonhosted.org/packages/04/8f/2551964ef045669801675f1cfc3b0d74147f4901c3ffa42be2ddb1f0efc4/pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:c8e7af2f4e0194c22b5b37205bfb293d166a7344a5b0d0eaccebc376546d77d5", size = 2063196, upload-time = "2025-04-23T18:32:08.178Z" }, + { url = "https://files.pythonhosted.org/packages/26/bd/d9602777e77fc6dbb0c7db9ad356e9a985825547dce5ad1d30ee04903918/pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:5c92edd15cd58b3c2d34873597a1e20f13094f59cf88068adb18947df5455b4e", size = 2236389, upload-time = "2025-04-23T18:32:10.242Z" }, + { url = "https://files.pythonhosted.org/packages/42/db/0e950daa7e2230423ab342ae918a794964b053bec24ba8af013fc7c94846/pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:65132b7b4a1c0beded5e057324b7e16e10910c106d43675d9bd87d4f38dde162", size = 2239223, upload-time = "2025-04-23T18:32:12.382Z" }, + { url = "https://files.pythonhosted.org/packages/58/4d/4f937099c545a8a17eb52cb67fe0447fd9a373b348ccfa9a87f141eeb00f/pydantic_core-2.33.2-cp313-cp313-win32.whl", hash = "sha256:52fb90784e0a242bb96ec53f42196a17278855b0f31ac7c3cc6f5c1ec4811849", size = 1900473, upload-time = "2025-04-23T18:32:14.034Z" }, + { url = "https://files.pythonhosted.org/packages/a0/75/4a0a9bac998d78d889def5e4ef2b065acba8cae8c93696906c3a91f310ca/pydantic_core-2.33.2-cp313-cp313-win_amd64.whl", hash = "sha256:c083a3bdd5a93dfe480f1125926afcdbf2917ae714bdb80b36d34318b2bec5d9", size = 1955269, upload-time = "2025-04-23T18:32:15.783Z" }, + { url = "https://files.pythonhosted.org/packages/f9/86/1beda0576969592f1497b4ce8e7bc8cbdf614c352426271b1b10d5f0aa64/pydantic_core-2.33.2-cp313-cp313-win_arm64.whl", hash = "sha256:e80b087132752f6b3d714f041ccf74403799d3b23a72722ea2e6ba2e892555b9", size = 1893921, upload-time = "2025-04-23T18:32:18.473Z" }, + { url = "https://files.pythonhosted.org/packages/a4/7d/e09391c2eebeab681df2b74bfe6c43422fffede8dc74187b2b0bf6fd7571/pydantic_core-2.33.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:61c18fba8e5e9db3ab908620af374db0ac1baa69f0f32df4f61ae23f15e586ac", size = 1806162, upload-time = "2025-04-23T18:32:20.188Z" }, + { url = "https://files.pythonhosted.org/packages/f1/3d/847b6b1fed9f8ed3bb95a9ad04fbd0b212e832d4f0f50ff4d9ee5a9f15cf/pydantic_core-2.33.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:95237e53bb015f67b63c91af7518a62a8660376a6a0db19b89acc77a4d6199f5", size = 1981560, upload-time = "2025-04-23T18:32:22.354Z" }, + { url = "https://files.pythonhosted.org/packages/6f/9a/e73262f6c6656262b5fdd723ad90f518f579b7bc8622e43a942eec53c938/pydantic_core-2.33.2-cp313-cp313t-win_amd64.whl", hash = "sha256:c2fc0a768ef76c15ab9238afa6da7f69895bb5d1ee83aeea2e3509af4472d0b9", size = 1935777, upload-time = "2025-04-23T18:32:25.088Z" }, +] + +[[package]] +name = "sniffio" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a2/87/a6771e1546d97e7e041b6ae58d80074f81b7d5121207425c964ddf5cfdbd/sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc", size = 20372, upload-time = "2024-02-25T23:20:04.057Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235, upload-time = "2024-02-25T23:20:01.196Z" }, +] + +[[package]] +name = "starlette" +version = "0.47.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/04/57/d062573f391d062710d4088fa1369428c38d51460ab6fedff920efef932e/starlette-0.47.2.tar.gz", hash = "sha256:6ae9aa5db235e4846decc1e7b79c4f346adf41e9777aebeb49dfd09bbd7023d8", size = 2583948, upload-time = "2025-07-20T17:31:58.522Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f7/1f/b876b1f83aef204198a42dc101613fefccb32258e5428b5f9259677864b4/starlette-0.47.2-py3-none-any.whl", hash = "sha256:c5847e96134e5c5371ee9fac6fdf1a67336d5815e09eb2a01fdb57a351ef915b", size = 72984, upload-time = "2025-07-20T17:31:56.738Z" }, +] + +[[package]] +name = "toml" +version = "0.10.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/be/ba/1f744cdc819428fc6b5084ec34d9b30660f6f9daaf70eead706e3203ec3c/toml-0.10.2.tar.gz", hash = "sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f", size = 22253, upload-time = "2020-11-01T01:40:22.204Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/44/6f/7120676b6d73228c96e17f1f794d8ab046fc910d781c8d151120c3f1569e/toml-0.10.2-py2.py3-none-any.whl", hash = "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b", size = 16588, upload-time = "2020-11-01T01:40:20.672Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.14.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/98/5a/da40306b885cc8c09109dc2e1abd358d5684b1425678151cdaed4731c822/typing_extensions-4.14.1.tar.gz", hash = "sha256:38b39f4aeeab64884ce9f74c94263ef78f3c22467c8724005483154c26648d36", size = 107673, upload-time = "2025-07-04T13:28:34.16Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b5/00/d631e67a838026495268c2f6884f3711a15a9a2a96cd244fdaea53b823fb/typing_extensions-4.14.1-py3-none-any.whl", hash = "sha256:d1e1e3b58374dc93031d6eda2420a48ea44a36c2b4766a4fdeb3710755731d76", size = 43906, upload-time = "2025-07-04T13:28:32.743Z" }, +] + +[[package]] +name = "typing-inspection" +version = "0.4.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f8/b1/0c11f5058406b3af7609f121aaa6b609744687f1d158b3c3a5bf4cc94238/typing_inspection-0.4.1.tar.gz", hash = "sha256:6ae134cc0203c33377d43188d4064e9b357dba58cff3185f22924610e70a9d28", size = 75726, upload-time = "2025-05-21T18:55:23.885Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/17/69/cd203477f944c353c31bade965f880aa1061fd6bf05ded0726ca845b6ff7/typing_inspection-0.4.1-py3-none-any.whl", hash = "sha256:389055682238f53b04f7badcb49b989835495a96700ced5dab2d8feae4b26f51", size = 14552, upload-time = "2025-05-21T18:55:22.152Z" }, +] + +[[package]] +name = "uvicorn" +version = "0.35.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5e/42/e0e305207bb88c6b8d3061399c6a961ffe5fbb7e2aa63c9234df7259e9cd/uvicorn-0.35.0.tar.gz", hash = "sha256:bc662f087f7cf2ce11a1d7fd70b90c9f98ef2e2831556dd078d131b96cc94a01", size = 78473, upload-time = "2025-06-28T16:15:46.058Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d2/e2/dc81b1bd1dcfe91735810265e9d26bc8ec5da45b4c0f6237e286819194c3/uvicorn-0.35.0-py3-none-any.whl", hash = "sha256:197535216b25ff9b785e29a0b79199f55222193d47f820816e7da751e9bc8d4a", size = 66406, upload-time = "2025-06-28T16:15:44.816Z" }, +]