libtmux Documentation

repository·master·Indexed 22 days ago

https://github.com/tmux-python/libtmux

A typed, object-oriented Python library providing an ORM wrapper for tmux, a terminal multiplexer. It allows developers to programmatically manage tmux servers, sessions, windows, and panes through a hierarchy of Python objects (Server → Session → Window → Pane) instead of parsing CLI output. Features include the ability to send keys, capture pane output, discover environment context via Pane.from_env(), and a pytest plugin for isolated tmux testing.

Tokens
44.1K
Snippets
153
Records
211
Agent score
77%

What's inside libtmux

  1. Understand the libtmux object hierarchy

    master

    libtmux follows the hierarchical structure of a tmux server. You can navigate through related objects in both directions (down to children or up to parents):

    1. Server: The top-level object containing all sessions.
    2. Session: Groups one or more windows.
    3. Window: Groups one or more panes.
    4. Pane: The leaf node (the actual terminal area).

    Traversal Examples:

    • Downwards: Use properties like session.windows to list children.
    • Upwards: Use properties like pane.session to jump from a pane back to its parent session.

    Note: Accessing these properties queries tmux fresh every time. For performance in loops, bind the collection to a variable first.

    >>> # Downward traversal
    >>> session.windows
    [Window(...), ...]
    
    >>> # Upward traversal
    >>> pane.session
    Session($... ...)
    
    >>> # Full upward path
    >>> pane.window.session.server is server
    True
  2. Understand libtmux known limitations

    master

    When working with libtmux, be aware of the following operational constraints:

    • tmux availability: A tmux server must be running and accessible via the default socket or a specifically provided socket.
    • Session requirement: Certain operations require the tmux server to have at least one active session.
    • Format string dependency: The availability of specific format strings used by libtmux is strictly dependent on the version of tmux currently running.
  3. Understanding libtmux format-token fields

    master

    libtmux objects (such as Server, Session, Window, Pane, and Client) provide a flat set of typed string attributes that mirror tmux's built-in FORMATS tokens. For example, a Pane object provides attributes like pane.pane_id, pane.window_id, and pane.session_id directly from tmux state without requiring raw command execution.

    Important: Handling None values Not every field is populated on every object. A field will return None if:

    1. Version mismatch: The token was introduced in a newer version of tmux than the one currently running (e.g., pane.pane_dead_signal is None on tmux 3.2a because it requires 3.3+).
    2. Scope mismatch: The token does not apply to that specific object type (e.g., buffer_* tokens do not apply to Client rows).
    3. Live-only tokens: Tokens like mouse_*, cursor_*, or selection_* only resolve during live events (like copy-mode) and are excluded from standard list-* snapshots.

    You should always perform None checks when accessing attributes that might depend on specific tmux versions or object scopes.

  4. Understand the libtmux Client abstraction

    master

    In libtmux, a Client represents an attached terminal (the view a user sees). A single tmux server can host multiple clients simultaneously (e.g., from multiple tmux attach commands).

    Unlike the standard hierarchy (ServerSessionWindowPane), a Client is not an owner; it points at a Session, Window, or Pane that it is currently viewing.

    Key distinction: Identity vs. View

    • Identity: The client_name (the tty path) is the stable identity of the client for the lifetime of the attachment.
    • View: Fields like session_id, window_id, pane_id, and client_session are snapshots of what the client was viewing at the moment they were read. These become stale immediately if the user performs actions like switch-client, select-window, or `select-pane.
  5. How to manage long-running processes in libtmux

    master

    When you use Pane.send_keys(), the command runs in the background and control returns to your Python script immediately. To manage these processes, you must use the Pane object as your handle. Since send_keys() is non-blocking, you cannot rely on the function return value to know if a process is finished; instead, you must poll the pane's output using Pane.capture_pane() and look for specific text markers (e.g., echo "DONE") to determine the process state.

    import time
    
    # Start a background process
    proc_pane.send_keys('sleep 2 && echo "Process complete"')
    
    # The script continues immediately while the command runs in the pane
    time.sleep(0.1)
    # Use capture_pane() to check status later
  6. How to set up a workspace with libtmux

    master

    A workspace is a single window divided into multiple panes, each running a different program. You can build these layouts from Python using four primary methods:

    1. libtmux.Session.new_window: To open a new window.
    2. libtmux.Window.split: To divide a window into panes.
    3. libtmux.Window.select_layout: To arrange panes using built-in tmux layouts.
    4. libtmux.Pane.send_keys: To send commands to a specific pane.

    To follow along with examples, you need one terminal running a live tmux server (tmux) and another running a Python prompt to drive it.

    # Terminal 1: Start tmux
    $ tmux
    
    # Terminal 2: Start Python
    $ python
  7. Distinguish between public and internal libtmux APIs

    master

    To ensure your code remains stable across updates, you must distinguish between the public API and internal implementation details.

    • Public API: Any name you can import from the libtmux namespace without a leading underscore in its module path (e.g., libtmux.Session). These are covered by a deprecation policy and are safe to use.
    • Internal API: Any name containing a leading underscore in its module path (e.g., libtmux._internal.* or libtmux._vendor.*). These are implementation details that can change or be removed between any release without warning.

    Recommendation: Always stick to the public API. If you find yourself needing a feature that is currently only available in an _internal module, file an issue to request its promotion to the public API.

  8. Compare Python-side `.filter()` vs tmux-native `.search_*()`

    master

    Choose your filtering strategy based on data volume and complexity:

    Feature.filter().search_*()
    Execution LocationPython (after fetch)tmux server (before fetch)
    Filter Languagelibtmux lookup operators (__contains, __regex, etc.)tmux FORMATS grammar (#{...})
    EfficiencyOne round trip (fetches everything)One round trip (fetches only matches)
    Best Use CaseRich Python checks, complex regex, post-fetch compositionExact/glob matches over many rows
    RequirementsAny versionRequires tmux ≥ 3.2
  9. How libtmux tracks objects across refreshes

    master

    To ensure stability when tmux state changes (like indexes shifting), libtmux uses unique internal identifiers assigned by tmux. These are stored as attributes on each object, allowing libtmux to reliably track the same entity even after a state refresh.

    ObjectAttributePrefixExample
    Sessionsession_id$$13
    Windowwindow_id@@3243
    Panepane_id%%5433
  10. Identify the current pane from within a pane

    master
    If your Python code is running inside a tmux pane and you need to know which pane, window, session, or server it belongs to, use the 'Locating Yourself' pattern. This allows a script to discover its own context within the tmux environment.