Typed library that provides an ORM wrapper for tmux, a terminal multiplexer.
—
libtmux provides utility functions for version checking, tmux compatibility validation, session name validation, and other helper operations. These utilities support the core functionality and provide tools for applications built on libtmux.
Functions to detect tmux version and check compatibility requirements.
def get_version() -> LooseVersion:
"""
Return tmux version.
If tmux is built from git master, the version returned will be the latest
version appended with -master, e.g. 2.4-master.
If using OpenBSD's base system tmux, the version will have -openbsd
appended to the latest version, e.g. 2.4-openbsd.
Returns:
LooseVersion object containing tmux version
Raises:
TmuxCommandNotFound: If tmux binary not found
LibTmuxException: If version detection fails
VersionTooLow: If tmux version is too old
"""
def has_version(version: str) -> bool:
"""
Check if current tmux version matches exactly.
Parameters:
- version: Version string to match
Returns:
True if versions match exactly
"""
def has_gt_version(version: str) -> bool:
"""
Check if current tmux version is greater than specified version.
Parameters:
- version: Version string to compare against
Returns:
True if current version is greater
"""
def has_gte_version(version: str) -> bool:
"""
Check if current tmux version is greater than or equal to specified version.
Parameters:
- version: Version string to compare against
Returns:
True if current version is greater than or equal
"""
def has_lte_version(version: str) -> bool:
"""
Check if current tmux version is less than or equal to specified version.
Parameters:
- version: Version string to compare against
Returns:
True if current version is less than or equal
"""
def has_lt_version(version: str) -> bool:
"""
Check if current tmux version is less than specified version.
Parameters:
- version: Version string to compare against
Returns:
True if current version is less than
"""
def has_minimum_version(raises: bool = True) -> bool:
"""
Return True if tmux meets version requirement. Version >1.8 or above.
Parameters:
- raises: Raise exception if below minimum version requirement
Returns:
True if tmux meets minimum required version
Raises:
VersionTooLow: If tmux version below minimum required for libtmux and raises=True
"""Functions to get libtmux library version and metadata.
def get_libtmux_version() -> LooseVersion:
"""
Return libtmux version is a PEP386 compliant format.
Returns:
LooseVersion object containing libtmux version
"""Functions to validate and sanitize tmux session names.
def session_check_name(session_name: str | None) -> None:
"""
Raise exception session name invalid, modeled after tmux function.
tmux(1) session names may not be empty, or include periods or colons.
These delimiters are reserved for noting session, window and pane.
Parameters:
- session_name: Name of session
Raises:
BadSessionName: Invalid session name
"""Functions to process and handle tmux command errors.
def handle_option_error(error: str) -> type[OptionError]:
"""
Raise exception if error in option command found.
In tmux 3.0, show-option and show-window-option return invalid option instead of
unknown option.
In tmux >2.4, there are 3 different types of option errors:
- unknown option
- invalid option
- ambiguous option
In tmux <2.4, unknown option was the only option.
All errors raised will have the base error of OptionError. So to
catch any option error, use except OptionError.
Parameters:
- error: Error response from subprocess call
Raises:
OptionError, UnknownOption, InvalidOption, AmbiguousOption
"""Low-level command execution and process management.
class tmux_cmd:
"""
Run any tmux(1) command through subprocess.
Attributes:
- cmd: Command that was executed
- stdout: Command stdout as list of strings
- stderr: Command stderr as list of strings
- returncode: Process return code
- process: Subprocess.Popen object
"""
def __init__(self, *args: t.Any) -> None:
"""
Execute tmux command.
Parameters:
- *args: Command arguments (converted to strings)
Raises:
TmuxCommandNotFound: If tmux binary not found in PATH
"""Mixin class providing environment variable operations for sessions.
class EnvironmentMixin:
"""Mixin for manager session and server level environment variables in tmux."""
def __init__(self, add_option: str | None = None) -> None:
"""Initialize mixin with optional add_option for command scope."""
def set_environment(self, name: str, value: str) -> None:
"""
Set environment $ tmux set-environment <name> <value>.
Parameters:
- name: Environment variable name (e.g., 'PATH')
- value: Environment variable value
Raises:
ValueError: If tmux command returns error
"""
def unset_environment(self, name: str) -> None:
"""
Unset environment variable $ tmux set-environment -u <name>.
Parameters:
- name: Environment variable name (e.g., 'PATH')
Raises:
ValueError: If tmux command returns error
"""
def remove_environment(self, name: str) -> None:
"""
Remove environment variable $ tmux set-environment -r <name>.
Parameters:
- name: Environment variable name (e.g., 'PATH')
Raises:
ValueError: If tmux command returns error
"""
def show_environment(self) -> dict[str, bool | str]:
"""
Show environment $ tmux show-environment -t [session].
Return dict of environment variables for the session.
Returns:
Dictionary of environmental variables
"""
def getenv(self, name: str) -> str | bool | None:
"""
Show environment variable $ tmux show-environment -t [session] <name>.
Return the value of a specific variable if the name is specified.
Parameters:
- name: Environment variable name (e.g., 'PATH')
Returns:
Value of environment variable or None if not found
"""Version compatibility and feature support constants.
TMUX_MIN_VERSION: str = "1.8"
"""Minimum version of tmux required to run libtmux."""
TMUX_MAX_VERSION: str = "3.4"
"""Most recent version of tmux supported."""
# Type definitions
SessionDict = dict[str, t.Any]
WindowDict = dict[str, t.Any]
WindowOptionDict = dict[str, t.Any]
PaneDict = dict[str, t.Any]import libtmux.common as common
# Get current tmux version
try:
version = common.get_version()
print(f"tmux version: {version}")
except TmuxCommandNotFound:
print("tmux not found")
# Check version compatibility
if common.has_minimum_version("2.0"):
print("tmux supports modern features")
else:
print("tmux version is too old")
# Feature-specific version checks
if common.has_gte_version("2.1"):
# Use features introduced in 2.1+
pass
if common.has_lt_version("3.0"):
# Handle older tmux versions
passimport libtmux.common as common
from libtmux.exc import BadSessionName
session_names = ["valid-name", "invalid:name", "another$bad", "good_name"]
for name in session_names:
try:
validated = common.session_check_name(name)
print(f"'{name}' -> '{validated}' (valid)")
except BadSessionName as e:
print(f"'{name}' is invalid: {e}")import libtmux.common as common
# Execute raw tmux command
cmd = common.tmux_cmd(['list-sessions'])
if cmd.returncode == 0:
print("Sessions:")
for line in cmd.stdout:
print(f" {line}")
else:
print("Error:", cmd.stderr)import libtmux.common as common
# Get library version
lib_version = common.get_libtmux_version()
tmux_version = common.get_version()
print(f"libtmux version: {lib_version}")
print(f"tmux version: {tmux_version}")
# Check compatibility matrix
min_version = common.TMUX_MIN_VERSION
max_version = common.TMUX_MAX_VERSION
print(f"Supported tmux versions: {min_version} - {max_version}")import libtmux
# EnvironmentMixin is used by Session class
server = libtmux.Server()
session = server.new_session('env_test')
# Set environment variables
session.set_environment('PROJECT_ROOT', '/home/user/project')
session.set_environment('DEBUG_MODE', '1')
# Get environment variables
project_root = session.getenv('PROJECT_ROOT')
all_env = session.show_environment()
print(f"Project root: {project_root}")
print("All environment variables:")
for key, value in all_env.items():
print(f" {key}={value}")
# Clean up
session.unset_environment('DEBUG_MODE')import libtmux.common as common
from libtmux.exc import UnknownOption, InvalidOption
# Example of option error handling
try:
# This would normally be called internally by libtmux
common.handle_option_error(
"unknown option: invalid-option",
"invalid-option",
"some-value"
)
except UnknownOption as e:
print(f"Option '{e.option}' is not recognized by tmux")
try:
common.handle_option_error(
"invalid value for option",
"mouse",
"invalid-value"
)
except InvalidOption as e:
print(f"Invalid value '{e.value}' for option '{e.option}'")import libtmux
import libtmux.common as common
from libtmux.exc import LibTmuxException
def setup_development_environment():
"""Set up a development environment with version checking."""
# Check tmux availability and version
try:
version = common.get_version()
print(f"Found tmux version: {version}")
if not common.has_minimum_version("2.0"):
print("Warning: tmux version may not support all features")
except Exception as e:
print(f"tmux not available: {e}")
return None
# Validate session name
try:
session_name = common.session_check_name("dev-environment")
except Exception as e:
print(f"Invalid session name: {e}")
session_name = "dev_environment"
# Create session with environment
try:
server = libtmux.Server()
session = server.new_session(session_name)
# Set up environment
session.set_environment('DEV_MODE', '1')
session.set_environment('TMUX_VERSION', version)
session.set_environment('LIBTMUX_VERSION', common.get_libtmux_version())
print(f"Development environment '{session_name}' created successfully")
return session
except LibTmuxException as e:
print(f"Failed to create development environment: {e}")
return None
# Usage
dev_session = setup_development_environment()
if dev_session:
print("Development environment ready!")Install with Tessl CLI
npx tessl i tessl/pypi-libtmux