Typed library that provides an ORM wrapper for tmux, a terminal multiplexer.
—
Session management in libtmux handles tmux session operations, window collections, environment variables, and session-level configuration. Sessions represent collections of windows and provide isolated environments for terminal workflows.
Create and manage session instances with proper resource management and context support.
@dataclasses.dataclass()
class Session(Obj, EnvironmentMixin):
"""
tmux Session object.
Holds Window objects and inherits from Obj and EnvironmentMixin.
"""
server: Server
def __enter__(self) -> Self:
"""Enter the context, returning self."""
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
exc_tb: types.TracebackType | None
) -> None:
"""Exit the context, killing the session if it exists."""
@classmethod
def from_session_id(cls, server: Server, session_id: str) -> Session:
"""Create Session from existing session_id."""Access and update session state and attributes from tmux.
def refresh(self) -> None:
"""Refresh session attributes from tmux."""
@property
def id(self) -> str | None:
"""Alias of Session.session_id."""
@property
def name(self) -> str | None:
"""Alias of Session.session_name."""
@property
def active_pane(self) -> Pane | None:
"""Return the active Pane object."""
@property
def active_window(self) -> Window:
"""Return the active Window object."""Execute tmux commands within the session context.
def cmd(
self,
cmd: str,
*args: t.Any,
target: str | int | None = None
) -> tmux_cmd:
"""
Execute tmux subcommand within session context.
Automatically binds target by adding -t for object's session ID to the command.
Parameters:
- cmd: The tmux command to execute
- *args: Additional command arguments
- target: Optional custom target override (defaults to session ID)
Returns:
tmux_cmd object with stdout, stderr, and return code
"""Create, manage, and query windows within the session.
def new_window(
self,
window_name: str | None = None,
*,
start_directory: StrPath | None = None,
attach: bool = False,
window_index: str = "",
window_shell: str | None = None,
environment: dict[str, str] | None = None,
direction: WindowDirection | None = None,
target_window: str | None = None
) -> Window:
"""
Create new window, returns new Window.
By default, this will make the window active. For the new window
to be created and not set to current, pass in attach=False.
Parameters:
- window_name: Name for the new window
- start_directory: Working directory in which the new window is created
- attach: Make new window the current window after creating it (default False)
- window_index: Create window at given index position (empty string for next available)
- window_shell: Execute command on starting the window
- environment: Environment variables for window (tmux 3.0+)
- direction: Insert window before or after target window (tmux 3.2+)
- target_window: Used by Window.new_window to specify target window
Returns:
Window object for the created window
"""
def select_window(self, target_window: str | int) -> Window:
"""
Select window and return the selected window.
Parameters:
- target_window: Window name/index, or 'last-window', 'next-window', 'previous-window'
Returns:
Selected Window object
"""
def kill_window(self, target_window: str | None = None) -> None:
"""
Close a tmux window, and all panes inside it.
Kill the current window or the window at target-window, removing it
from any sessions to which it is linked.
Parameters:
- target_window: Window to kill (optional)
"""Control session attachment, detachment, renaming, and termination.
def attach(
self,
exit_: bool | None = None,
flags_: list[str] | None = None
) -> Session:
"""
Return tmux attach-session (alias: tmux attach).
Parameters:
- exit_: Exit the client after attaching session
- flags_: Additional flags to pass to attach-session
Returns:
Session instance for method chaining
"""
def kill(
self,
all_except: bool | None = None,
clear: bool | None = None
) -> None:
"""
Kill Session, closes linked windows and detach all clients.
Parameters:
- all_except: Kill all sessions in server except this one
- clear: Clear alerts (bell, activity, or silence) in all windows
"""
def rename_session(self, new_name: str) -> Session:
"""
Rename session and return new Session object.
Parameters:
- new_name: New session name
Returns:
Session instance for method chaining
Raises:
BadSessionName: If session name is invalid
"""
def switch_client(self) -> Session:
"""
Switch client to session.
Returns:
Session instance for method chaining
Raises:
LibTmuxException: If tmux command fails
"""Configure session-level tmux options and settings.
def set_option(
self,
option: str,
value: str | int,
global_: bool = False
) -> Session:
"""
Set option $ tmux set-option <option> <value>.
Parameters:
- option: The session option (e.g., 'default-shell')
- value: Option value (True/False becomes 'on'/'off')
- global_: Check for option globally across all servers (-g)
Returns:
Session instance for method chaining
Raises:
OptionError, UnknownOption, InvalidOption, AmbiguousOption
"""
def show_options(
self,
global_: bool | None = False
) -> dict[str, str | int]:
"""
Return dict of options for the session.
Parameters:
- global_: Pass -g flag for global variable (server-wide)
Returns:
Dictionary of option names and values
"""
def show_option(
self,
option: str,
global_: bool = False
) -> str | int | bool | None:
"""
Return option value for the target session.
Parameters:
- option: Option name
- global_: Use global option scope, same as -g
Returns:
Option value (str, int, bool, or None if not found)
Raises:
OptionError, UnknownOption, InvalidOption, AmbiguousOption
"""Manage session-level environment variables through inherited EnvironmentMixin.
# Inherited from EnvironmentMixin
def set_environment(self, name: str, value: str) -> Session:
"""Set environment variable for session."""
def unset_environment(self, name: str) -> Session:
"""Unset environment variable for session."""
def remove_environment(self, name: str) -> Session:
"""Remove environment variable from session."""
def show_environment(self, global_: bool = False) -> dict[str, str]:
"""Get all environment variables as dictionary."""
def getenv(self, name: str) -> str | None:
"""Get specific environment variable value."""Access collections of windows and panes within the session.
@property
def windows(self) -> QueryList[Window]:
"""QueryList of windows in session."""
@property
def panes(self) -> QueryList[Pane]:
"""QueryList of all panes across session's windows."""import libtmux
server = libtmux.Server()
session = server.new_session('my_session')
# Get session information
print(f"Session ID: {session.id}")
print(f"Session Name: {session.name}")
# Refresh session state
session.refresh()import libtmux
server = libtmux.Server()
with server.new_session('temp_session') as session:
# Work with session
window = session.new_window('work')
# Session automatically cleaned up on exitimport libtmux
server = libtmux.Server()
session = server.new_session('dev')
# Create windows
editor = session.new_window('editor', window_command='vim')
terminal = session.new_window('terminal')
logs = session.new_window('logs', start_directory='/var/log')
# Query windows
for window in session.windows:
print(f"Window: {window.name}")
# Find specific windows
vim_windows = session.find_where(window_name='editor')import libtmux
server = libtmux.Server()
session = server.new_session('env_test')
# Set environment variables
session.set_environment('PROJECT_ROOT', '/home/user/project')
session.set_environment('DEBUG', '1')
# Get environment variables
project_root = session.getenv('PROJECT_ROOT')
all_env = session.show_environment()
# Clean up environment
session.unset_environment('DEBUG')import libtmux
server = libtmux.Server()
session = server.new_session('configured')
# Set session options
session.set_option('mouse', 'on')
session.set_option('base-index', '1')
# Get options
mouse_setting = session.show_option('mouse')
all_options = session.show_options()Install with Tessl CLI
npx tessl i tessl/pypi-libtmux