Typed library that provides an ORM wrapper for tmux, a terminal multiplexer.
—
Server management in libtmux handles tmux server connections, lifecycle operations, and global server-level functionality. The Server class provides methods to connect to tmux servers, manage sessions across the server, and execute server-wide commands.
Create and configure connections to tmux servers with support for custom socket paths, configuration files, and color settings.
class Server:
def __init__(
self,
socket_name: str | None = None,
socket_path: str | pathlib.Path | None = None,
config_file: str | None = None,
colors: int | None = None,
on_init: t.Callable[[Server], None] | None = None,
socket_name_factory: t.Callable[[], str] | None = None,
**kwargs: t.Any
) -> None:
"""
Initialize tmux server connection.
Parameters:
- socket_name: Named socket identifier for tmux server
- socket_path: Full path to tmux socket file or Path object
- config_file: Path to tmux configuration file
- colors: Color support (256 or 88)
- on_init: Callback function called after initialization
- socket_name_factory: Factory function to generate socket name
- **kwargs: Additional keyword arguments
"""
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 server if it exists."""Check server connection status and ensure server availability for operations.
def is_alive(self) -> bool:
"""Check if tmux server is running and accessible."""
def raise_if_dead(self):
"""Raise TmuxCommandNotFound if server is not running."""Execute tmux commands within the server context with proper error handling and output capture.
def cmd(
self,
cmd: str,
*args: t.Any,
target: str | int | None = None
) -> tmux_cmd:
"""
Execute tmux command on server.
Parameters:
- cmd: The tmux command to execute
- *args: Additional command arguments
- target: Optional target for the command
Returns:
tmux_cmd object with stdout, stderr, and return code
"""Create, manage, and query sessions on the tmux server.
def new_session(
self,
session_name: str | None = None,
kill_session: bool = False,
attach: bool = False,
start_directory: StrPath | None = None,
window_name: str | None = None,
window_command: str | None = None,
x: int | DashLiteral | None = None,
y: int | DashLiteral | None = None,
environment: dict[str, str] | None = None,
*args: t.Any,
**kwargs: t.Any
) -> Session:
"""
Create new tmux session.
Parameters:
- session_name: Name for the new session
- kill_session: Kill existing session if it exists
- attach: Whether to attach to session after creation
- start_directory: Starting directory for session (str or PathLike)
- window_name: Name for initial window
- window_command: Command to run in initial window
- x: Force specified width for detached session
- y: Force specified height for detached session
- environment: Environment variables to set (tmux 3.2+)
- *args: Additional positional arguments
- **kwargs: Additional keyword arguments
Returns:
Session object for the created session
Raises:
TmuxSessionExists: If session name already exists and kill_session=False
BadSessionName: If session name is invalid
"""
def has_session(self, target_session: str, exact: bool = True) -> bool:
"""
Check if session exists by name or ID.
Parameters:
- target_session: Session name to check
- exact: Match session name exactly (tmux 2.1+)
Returns:
True if session exists, False otherwise
Raises:
BadSessionName: If session name is invalid
"""
def kill_session(self, target_session: str | int) -> Server:
"""
Kill session by name or ID.
Parameters:
- target_session: Session name or ID to kill
Returns:
Server instance for method chaining
Raises:
BadSessionName: If session name is invalid
LibTmuxException: If tmux command fails
"""
def attach_session(self, target_session: str | None = None) -> None:
"""
Attach to existing session.
Parameters:
- target_session: Session name to attach to
Raises:
BadSessionName: If session name is invalid
LibTmuxException: If tmux command fails
"""
def switch_client(self, target_session: str) -> None:
"""
Switch client to different session.
Parameters:
- target_session: Session name to switch to
Raises:
BadSessionName: If session name is invalid
LibTmuxException: If tmux command fails
"""Terminate the entire tmux server and all associated sessions.
def kill(self):
"""Kill tmux server and all sessions."""Access collections of tmux objects across the entire server.
@property
def sessions(self) -> QueryList[Session]:
"""QueryList of all sessions on server."""
@property
def windows(self) -> QueryList[Window]:
"""QueryList of all windows across all sessions."""
@property
def panes(self) -> QueryList[Pane]:
"""QueryList of all panes across all sessions."""
@property
def attached_sessions(self) -> List[Session]:
"""List of currently attached sessions."""Access server configuration and connection details.
socket_name: str | None
"""Socket name for tmux server connection. Passthrough to [-L socket-name]."""
socket_path: str | pathlib.Path | None
"""Full socket path for tmux server connection. Passthrough to [-S socket-path]."""
config_file: str | None
"""Path to tmux configuration file. Passthrough to [-f file]."""
colors: int | None
"""Color support level (256 or 88)."""
child_id_attribute: str
"""Unique child ID used by TmuxRelationalObject."""
formatter_prefix: str
"""Namespace used for TmuxMappingObject."""import libtmux
# Connect to default tmux server
server = libtmux.Server()
# Connect to named socket
server = libtmux.Server(socket_name='my_socket')
# Connect with custom configuration
server = libtmux.Server(
socket_name='dev_socket',
config_file='~/.tmux-dev.conf',
colors=256
)import libtmux
with libtmux.Server() as server:
session = server.new_session('work')
# Server automatically cleaned up on exitimport libtmux
server = libtmux.Server()
# Create new session
session = server.new_session(
session_name='development',
window_name='editor',
start_directory='/home/user/projects'
)
# Check if session exists
if server.has_session('development'):
print("Session exists")
# List all sessions
for session in server.sessions:
print(f"Session: {session.name}")
# Kill specific session
server.kill_session('development')Install with Tessl CLI
npx tessl i tessl/pypi-libtmux