On this page
Python API reference
2005 symbols, extracted from source. Every type name in a signature links to its own entry; every cross-reference in a doc comment resolves against the same table.
By module 26 modules
- libtmux 14
- libtmux.__about__ 4
- libtmux._compat 9
- libtmux.client 1
- libtmux.common 25
- libtmux.constants 11
- libtmux.exc 29
- libtmux.formats 5
- libtmux.hooks 4
- libtmux.neo 19
- libtmux.options 18
- libtmux.pane 1
- libtmux.pytest_plugin 14
- libtmux.server 3
- libtmux.session 1
- libtmux.window 1
- libtmux._internal.constants 9
- libtmux._internal.control_mode 1
- libtmux._internal.dataclasses 1
- libtmux._internal.env 5
- libtmux._internal.query_list 21
- libtmux._internal.sparse_array 4
- libtmux._internal.types 1
- libtmux._vendor._structures 4
- libtmux._vendor.version 19
- Types 2
Server 1 type
Session 1 type
Window 2 types
Pane 2 types
Client 1 type
Options 2 types
Layout and geometry 1 type
Environment 1 type
Versions 3 types
Commands 3 types
Errors 20 types
Raised when a version string is not a valid version.
_TmuxVersionUnavailable 0 members Internal signal: this tmux predates the -V flag (pre-1.7).
Base Exception for libtmux Errors.
DeprecatedError 2 membersRaised when a deprecated function, method, or parameter is used.
TmuxCommandNotFound 2 membersApplication binary for tmux not found.
NotInsideTmux 2 membersRaised when the process is not running inside a tmux pane.
ObjectDoesNotExist 2 membersA lookup expected one object and matched none.
MultipleObjectsReturned 2 membersA lookup expected one object and matched several.
TmuxObjectDoesNotExist 2 memberstmux has no object with the id that was asked for.
VersionTooLow 2 membersRaised if tmux below the minimum version to use libtmux.
OptionError 2 membersRoot error for any error involving invalid, ambiguous or bad options.
UnknownOption 2 membersOption unknown to tmux show-option(s) or show-window-option(s).
UnknownColorOption 2 membersUnknown color option.
InvalidOption 2 membersOption invalid to tmux.
AmbiguousOption 2 membersOption that could potentially match more than one.
WaitTimeout 2 membersFunction timed out without meeting condition.
TmuxTimeout 1 membersA tmux command did not return within its timeout.
VariableUnpackingError 2 membersError unpacking variable.
AdjustmentDirectionRequiresAdjustment 2 membersIf *adjustment_direction* is set, *adjustment* must be set.
RequiresDigitOrPercentage 2 membersRequires digit (int or str digit) or a percentage.
Errors — Session 2 types
Errors — Window 5 types
Any type of window related error.
MultipleActiveWindows 2 membersMultiple active windows.
NoActiveWindow 2 membersNo active window found.
NoWindowsExist 2 membersNo windows exist for object.
WindowAdjustmentDirectionRequiresAdjustment 2 members ValueError for libtmux.Window.resize_window.
Errors — Pane 3 types
Internal 7 types
tmux hooks data structure.
ControlMode 9 membersContext manager that spawns a tmux control-mode client.
SkipDefaultFieldsReprMixin 1 members Skip default fields in dataclass object representation.
Filter list of object/dictionaries. For small, local datasets.
SparseArray 4 members Support non-sequential indexes while maintaining list -like behavior.
Internal — Options 5 types
Container for tmux server options.
SessionOptions 55 membersContainer for tmux session options.
WindowOptions 48 membersContainer for tmux window options.
PaneOptions 19 membersContainer for tmux pane options.
Options 136 membersContainer for all tmux options (server, session, window, and pane).
Other 4 types
Functions and constants 0 types
- __all__ = ( "Client", "Pane", "Server", "Session", "Window", "__author__", "__copyright__", "__description__", "__email__", "__license__", "__package_name__", "__title__", "__version__", )
- __email__ = "[email protected]"
- _legacy_version_component_re = re.compile(r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE)
- _legacy_version_replacement_map = { "pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@", }
- _SCOPE_OVERRIDES : dict[str, str] = { "cursor_x": "pane", # ft->wp->base.cx "cursor_y": "pane", # ft->wp->base.cy "cursor_flag": "pane", # ft->wp->base.mode "cursor_character": "pane", # ft->wp "mouse_all_flag": "pane", # ft->wp->base.mode MODE_MOUSE_ALL "mouse_any_flag": "pane", # ft->wp->base.mode ALL_MOUSE_MODES "mouse_button_flag": "pane", # ft->wp->base.mode MODE_MOUSE_BUTTON "mouse_sgr_flag": "pane", # ft->wp->base.mode MODE_MOUSE_SGR "mouse_standard_flag": "pane", # ft->wp->base.mode MODE_MOUSE_STANDARD "scroll_region_lower": "pane", # ft->wp->base.rlower "scroll_region_upper": "pane", # ft->wp->base.rupper "alternate_saved_x": "pane", # ft->wp->base.saved_cx "alternate_saved_y": "pane", # ft->wp->base.saved_cy "history_bytes": "pane", # ft->wp "history_limit": "pane", # ft->wp->base.grid->hlimit "history_size": "pane", # ft->wp->base.grid->hsize "insert_flag": "pane", # ft->wp->base.mode MODE_INSERT "keypad_cursor_flag": "pane", # ft->wp->base.mode MODE_KCURSOR "keypad_flag": "pane", # ft->wp->base.mode MODE_KKEYPAD "origin_flag": "pane", # ft->wp->base.mode MODE_ORIGIN "wrap_flag": "pane", # ft->wp->base.mode MODE_WRAP "active_window_index": "session", # ft->s->curw->idx "last_window_index": "session", # ft->s # tmux 3.7 pane-scope tokens that don't carry the pane_ prefix. "bracket_paste_flag": "pane", # ft->wp->screen->mode MODE_BRACKETPASTE "synchronized_output_flag": "pane", # ft->wp->base.mode MODE_SYNC }
- _SCOPE_PREFIXES : tuple[tuple[str, str], ...] = ( ("copy_cursor_", "event"), ("pane_", "pane"), ("window_", "window"), ("session_", "session"), ("client_", "client"), ("buffer_", "buffer"), ("mouse_", "event"), ("cursor_", "event"), ("selection_", "event"), ("scroll_", "event"), ("popup_", "event"), )
- _Version = collections.namedtuple( "_Version", ["epoch", "release", "dev", "pre", "post", "local"], )
- _VERSION_PATTERN = r""" v? (?: (?:(?P<epoch>[0-9]+)!)? # epoch (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment (?P<pre> # pre-release [-_\.]? (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview)) [-_\.]? (?P<pre_n>[0-9]+)? )? (?P<post> # post release (?:-(?P<post_n1>[0-9]+)) | (?: [-_\.]? (?P<post_l>post|rev|r) [-_\.]? (?P<post_n2>[0-9]+)? ) )? (?P<dev> # dev release [-_\.]? (?P<dev_l>dev) [-_\.]? (?P<dev_n>[0-9]+)? )? ) (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version """
- CLIENT_FORMATS = [ "client_cwd", "client_height", "client_width", "client_tty", "client_termname", "client_created", "client_created_string", "client_activity", "client_activity_string", "client_prefix", "client_utf8", "client_readonly", "client_session", "client_last_session", ]
- CmpKey = tuple[ int, tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType, ]
- ConvertedValues : TypeAlias = ( ConvertedValue | list[ConvertedValue] | dict[str, ConvertedValue] | SparseArray[ConvertedValue] )
- DEFAULT_OPTION_SCOPE : _DefaultOptionScope = _DefaultOptionScope()
- ExplodedComplexUntypedOptionsDict : TypeAlias = dict[ str, str | int | list[str | int] | dict[str, list[str | int]] | SparseArray[str | int] | None, ]
- ExplodedUntypedOptionsDict : TypeAlias = dict[ str, str | int | list[str] | dict[str, list[str]], ]
- FIELD_VERSION : dict[str, str] = { # Post-3.2a additions (verified against tmux's format.c at each gated # release tag, e.g. https://github.com/tmux/tmux/blob/3.6a/format.c). "pane_dead_signal": "3.3", "pane_dead_time": "3.3", # tmux 3.7 additions (verified against format.c / tmux.1 at the 3.7 tag). "bracket_paste_flag": "3.7", "pane_flags": "3.7", "pane_floating_flag": "3.7", "pane_pb_progress": "3.7", "pane_pb_state": "3.7", "pane_pipe_pid": "3.7", "pane_x": "3.7", "pane_y": "3.7", "pane_z": "3.7", "pane_zoomed_flag": "3.7", "synchronized_output_flag": "3.7", }
-
Minimum tmux version that registers each format token.
Field names absent from this dict default to
"3.2a"(always-safe within the supported tmux range). Entries here represent tokens added after 3.2a that need explicit gating to keep the-Ftemplate compatible with older tmux versions.
- HOOK_SCOPE_FLAG_MAP : dict[OptionScope, str] = { OptionScope.Server: "-g", OptionScope.Session: "", OptionScope.Window: "-w", OptionScope.Pane: "-p", }
- LocalTuple = ( SubLocalType | tuple[SubLocalType, str] | tuple[NegativeInfinityType, SubLocalType] )
- LOOKUP_NAME_MAP : Mapping[str, LookupProtocol] = { "eq": lookup_exact, "exact": lookup_exact, "iexact": lookup_iexact, "contains": lookup_contains, "icontains": lookup_icontains, "startswith": lookup_startswith, "istartswith": lookup_istartswith, "endswith": lookup_endswith, "iendswith": lookup_iendswith, "in": lookup_in, "nin": lookup_nin, "regex": lookup_regex, "iregex": lookup_iregex, }
- OPTION_SCOPE_FLAG_MAP : dict[OptionScope, str] = { OptionScope.Server: "-s", OptionScope.Session: "", OptionScope.Window: "-w", OptionScope.Pane: "-p", }
- PANE_DIRECTION_FLAG_MAP : dict[PaneDirection, list[str]] = { # -v is assumed, but for explicitness it is passed PaneDirection.Above: ["-v", "-b"], PaneDirection.Below: ["-v"], PaneDirection.Right: ["-h"], PaneDirection.Left: ["-h", "-b"], }
- PANE_FORMATS = [ "history_size", "history_limit", "history_bytes", "pane_index", "pane_width", "pane_height", "pane_title", "pane_id", "pane_active", "pane_dead", "pane_in_mode", "pane_synchronized", "pane_tty", "pane_pid", "pane_start_command", "pane_start_path", "pane_current_path", "pane_current_command", "cursor_x", "cursor_y", "scroll_region_upper", "scroll_region_lower", "saved_cursor_x", "saved_cursor_y", "alternate_on", "alternate_saved_x", "alternate_saved_y", "cursor_flag", "insert_flag", "keypad_cursor_flag", "keypad_flag", "wrap_flag", "mouse_standard_flag", "mouse_button_flag", "mouse_any_flag", "mouse_utf8_flag", # tmux 3.7 "pane_flags", "pane_floating_flag", "pane_x", "pane_y", "pane_z", "pane_zoomed_flag", "pane_pb_progress", "pane_pb_state", "pane_pipe_pid", "bracket_paste_flag", "synchronized_output_flag", ]
- RESIZE_ADJUSTMENT_DIRECTION_FLAG_MAP : dict[ResizeAdjustmentDirection, str] = { ResizeAdjustmentDirection.Up: "-U", ResizeAdjustmentDirection.Down: "-D", ResizeAdjustmentDirection.Left: "-L", ResizeAdjustmentDirection.Right: "-R", }
- SCOPES_BY_LIST_CMD : dict[str, frozenset[str]] = { "list-sessions": frozenset({"universal", "session", "window", "pane"}), "list-windows": frozenset({"universal", "session", "window", "pane"}), "list-panes": frozenset({"universal", "session", "window", "pane"}), "list-clients": frozenset({"universal", "session", "window", "pane", "client"}), }
-
Format-token scopes a given tmux
list-*subcommand can resolve.A token whose scope is in the set is safe to include in that subcommand's
-Ftemplate. A token whose scope is *outside* the set may be unavailable for that command, so libtmux leaves it out.The relationship is asymmetric: when tmux lists a parent object, it can also report fields for that parent's active child. A session row can include its current window and active pane fields, and a client row can include the attached session, current window, and active pane.
clientscope is the exception in the other direction: it appears only inlist-clientsbecause session/window/pane listings do not have a client attachment to report.
- SESSION_FORMATS = [ "session_name", "session_windows", "session_width", "session_height", "session_id", "session_created", "session_created_string", "session_attached", # "session_grouped", Apparently unused in tmux. "session_group", ]
-
Environment variable tmux exports with
socket_path,server_pid,session_id.
-
Environment variable tmux exports with the pane's id, e.g.
%3.
-
A string containing the regular expression used to match a valid version.
The pattern is not anchored at either end, and is intended for embedding in larger expressions (for example, matching a version number as part of a file name). The regular expression should be compiled with the
re.VERBOSEandre.IGNORECASEflags set.:meta hide-value:
- WINDOW_DIRECTION_FLAG_MAP : dict[WindowDirection, str] = { WindowDirection.Before: "-b", WindowDirection.After: "-a", }
- WINDOW_FORMATS = [ # format_window() "window_id", "window_name", "window_width", "window_height", "window_layout", "window_panes", # format_winlink() "window_index", "window_flags", "window_active", "window_bell_flag", "window_activity_flag", "window_silence_flag", ]
- _best_winlink ( rows : OutputsRaw ) OutputRaw
-
Pick the winlink row tmux would select.
A
list-windowslisting enumerates winlinks --(session, index, window)edges -- not windows.link-windowcan attach one window to a session at several indexes at once, so the samewindow_idmay appear on several rows, each with a differentwindow_index.tmux selects the current winlink when it contains the window, otherwise the first.
#{window_active}identifies the current row, and the lowestwindow_indexis tmux's first -- chosen explicitly here, so the caller need not pre-sort the rows.Examples
One row is the whole answer:
>>> from libtmux.neo import _best_winlink >>> _best_winlink([{"window_id": "@0", "window_index": "1"}])["window_index"] '1'A window linked into one session twice gives two rows. When the session is sitting on the higher-indexed link, that is the one tmux acts on:
>>> _best_winlink([ ... {"window_id": "@0", "window_index": "1", "window_active": "0"}, ... {"window_id": "@0", "window_index": "5", "window_active": "1"}, ... ])["window_index"] '5'When the session is sitting on some *other* window, neither link is current, and tmux falls back to the first:
>>> _best_winlink([ ... {"window_id": "@0", "window_index": "1", "window_active": "0"}, ... {"window_id": "@0", "window_index": "5", "window_active": "0"}, ... ])["window_index"] '1'The fallback reads the lowest index, not the first row, so a listing that happened to arrive high-index-first still answers tmux's first:
>>> _best_winlink([ ... {"window_id": "@0", "window_index": "5", "window_active": "0"}, ... {"window_id": "@0", "window_index": "1", "window_active": "0"}, ... ])["window_index"] '1'- Parameters
-
-
rows ( OutputsRaw ) – Non-empty rows for one object id in one session. Order does not matter: the current winlink wins, otherwise the lowest
window_index.
-
- Returns
-
OutputRaw The row naming the winlink tmux would act on.
-
-
Wrap
fetch_objs: treat a not-yet-started server as empty.A fresh
Servercan be introspected viaServer.sessions,Server.windows, etc. before the daemon is up. Other tmux errors, such as socket permission failures, still propagate.
-
Render a
QueryList.getlookup back askey=valuetext.Examples
>>> from libtmux.exc import _format_query >>> _format_query({"pane_id": "%0"}) "pane_id='%0'">>> _format_query({"window_name": "shared", "window_index": "1"}) "window_name='shared', window_index='1'">>> _format_query({}) ''
-
Return True if the error indicates the tmux server is not running.
tmux signals this in two ways: 1. "no server running" (socket exists but no daemon is listening) 2. "error connecting to ... (No such file or directory)" (socket file is missing)
-
Return True if tmux failed because the
-ttarget does not exist.A live tmux server rejects an unknown target with
can't find <kind>: <target>on stderr (cmd_find_targetin tmux'scmd-find.c), for every object kind and every supported tmux version. Every *other* failure -- a stopped daemon, a missing socket, a permission error -- says something else, and stays aLibTmuxException.This is the mirror image of
libtmux.server._is_daemon_not_up_error: together they answer "is the object gone, or is the server gone?" from the same stderr text.Examples
>>> from libtmux.neo import _is_target_not_found_error >>> _is_target_not_found_error("can't find pane: %99") True >>> _is_target_not_found_error("can't find window: @99") True >>> _is_target_not_found_error("can't find session: $99") TrueA server that isn't there is a different answer:
>>> _is_target_not_found_error("no server running on /tmp/tmux-1000/default") False >>> _is_target_not_found_error( ... "error connecting to /tmp/tmux-1000/nope (No such file or directory)" ... ) False- Parameters
-
-
stderr_text ( str ) – tmux's stderr, as carried by the raised
LibTmuxException.
-
- Returns
-
bool True when the object named by
-tdoes not exist on a reachable server.
- _legacy_cmpkey ( version : str ) LegacyCmpKey
-
Return a synthetic version string when tmux lacks
-V.OpenBSD ships a
-V-less base tmux, so assume the maximum supported version; any other platform is genuinely too old.
- _normalize_tmux_version ( version : str ) LooseVersion
-
Convert a tmux version string into a comparable
LooseVersion.tmux master is reported as
"master"(or e.g."3.6a-master"); treat it as larger than any tagged release.Examples
>>> from libtmux.neo import _normalize_tmux_version >>> _normalize_tmux_version("3.6a") < _normalize_tmux_version("master") True >>> _normalize_tmux_version("3.2a") < _normalize_tmux_version("3.6a") True
-
Take a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
-
Return the raw
tmux -Vversion token, letter suffix intact.Runs
tmux -Vand extracts the version token (e.g."3.7a","master","next-3.8"). Not memoized --get_versionandget_version_streach cache their own result on top of this query.- Parameters
- Returns
-
str Raw version token from
tmux -V. - Raises
-
-
_TmuxVersionUnavailable – tmux predates the
-Vflag; callers apply_no_version_flag_fallback. -
VersionTooLow – tmux reported another error on
-V.
-
-
Kill the tmux daemon on
socket_nameand unlink the socket file.Invoked from the
serverandTestServerfixture finalizers to guarantee teardown even when the daemon has already exited (killis a no-op then) and the socket file was left on disk. tmux does not reliablyunlink(2)its socket on non-graceful exit, so/tmp/tmux-<uid>/otherwise accumulates stale entries across test runs.Conservative: suppresses
LibTmuxException/OSErroron both the kill and the unlink. A finalizer that raises replaces the real test failure with a cleanup error, and cleanup failures are not actionable (socket already gone, permissions changed, race with a concurrent pytest-xdist worker).
-
Regroup
-Foutput into one string per object.tmux writes one record per line, but any format value may itself contain a newline --
pane_current_pathfor a directory whose name has one -- and that splits the record across output lines. Iterating lines then handsparse_outputa fragment with too few values, which its strictziprejects, so one directory breaks every object on the server rather than the one pane in it.Regrouping on the separator is exact rather than merely better: the template from
get_output_formatterminates *every* field with a separator, so one record holds exactlyfield_countof them and a newline is never one. Nothing is split on newlines, so a value may contain any number of them, in any position.- Raises
-
-
LibTmuxException – If the values do not divide into whole records, which means a value contained the separator itself.
-
-
Resolve a format token's scope from its name.
Returns
"universal"for cross-scope tokens (e.g.version,socket_path,host). Returns"event"for runtime-only tokens that never appear in alist-*output (mouse, cursor, selection, popup). Returns"context"for tokens registered outsideformat.c's static table (only resolve in a specific command or mode context). Returns"pane"/"window"/"session"/"client"/"buffer"for scope-prefixed tokens.Fields that don't match any prefix, override, or known-token table fall back to
"unknown"."unknown"is intentionally absent from everySCOPES_BY_LIST_CMDentry, so an unclassified field is excluded from everylist-*-Ftemplate — preventing a future untracked field from being silently emitted under a list command where it might crash older tmux. Add such a field to_SCOPE_OVERRIDES(or the appropriate prefix / known-token table) to admit it.Examples
>>> from libtmux.neo import _token_scope >>> _token_scope("pane_id") 'pane' >>> _token_scope("window_zoomed_flag") 'window' >>> _token_scope("client_name") 'client' >>> _token_scope("version") 'universal' >>> _token_scope("mouse_x") 'event'Tokens whose name doesn't carry a scope prefix can still be scope-gated via
_SCOPE_OVERRIDES(verified against tmux'sformat_cb_*). The override also corrects prefix-misclassified tokens — e.g.mouse_all_flagis a per-pane mode bit, not a runtime mouse event:>>> _token_scope("mouse_all_flag") 'pane' >>> _token_scope("active_window_index") 'session'Context-only tokens (registered outside
format.c's static table) route to the"context"scope and are excluded from everylist-*-Ftemplate:>>> _token_scope("command_list_alias") 'context' >>> _token_scope("search_match") 'context'Unclassified tokens fall back to
"unknown", also excluded from every list command:>>> _token_scope("libtmux_test_nonexistent_token") 'unknown'
-
Clear out any unnecessary environment variables that could interrupt tests.
tmux show-environment tests were being interrupted due to a lot of crazy env vars.
- config_file ( user_path : pathlib.Path ) pathlib.Path
-
Return fixture for
.tmux.confconfiguration.-
base-index -g 1
These guarantee pane and windows targets can be reliably referenced and asserted.
Note: You will need to set the home directory, see set_home.
-
- control_mode ( server : Server , session : Session ) t.Callable[[], ControlMode]
-
Return
ControlModecontext manager factory.Returns a callable that creates
ControlModecontext managers bound to the test's server and session. Use as a context manager to spawn a control-mode tmux client.While the control-mode client is active,
Server.list_clients()will include it.Examples
>>> from libtmux._internal.control_mode import ControlMode >>> def test_example(control_mode): ... with control_mode() as ctl: ... assert ctl.client_name != ''
-
Convert raw option strings to python types.
Examples
>>> convert_value("on") True >>> convert_value("off") False>>> convert_value("1") 1 >>> convert_value("50") 50>>> convert_value("%50") '%50'
-
Recursively convert values to python types via
convert_value.>>> convert_values(None)
>>> convert_values("on") True >>> convert_values("off") False
>>> convert_values(["on"]) [True] >>> convert_values(["off"]) [False]
>>> convert_values({"window_index": "1"}) {'window_index': 1}
>>> convert_values({"visual-bell": "on"}) {'visual-bell': True}
- explode_arrays ( _dict : UntypedOptionsDict , force_array : bool = False ) ExplodedUntypedOptionsDict
-
Explode flat, naive options dict's option arrays.
Examples
>>> import io>>> many_more_options = io.StringIO(r''' ... terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus ... terminal-features[1] screen*:title ... ''') >>> many_more_flat_dict = parse_options_to_dict(many_more_options) >>> many_more_flat_dict == { ... "terminal-features[0]": "xterm*:clipboard:ccolour:cstyle:focus", ... "terminal-features[1]": "screen*:title",} True >>> explode_arrays(many_more_flat_dict) == { ... "terminal-features": {0: "xterm*:clipboard:ccolour:cstyle:focus", ... 1: "screen*:title"}} Truetmux arrays allow non-sequential indexes, so we need to support that:
>>> explode_arrays(parse_options_to_dict(io.StringIO(r''' ... terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus ... terminal-features[5] screen*:title ... '''))) == { ... "terminal-features": {0: "xterm*:clipboard:ccolour:cstyle:focus", ... 5: "screen*:title"}} TrueUse
force_array=Truefor hooks, which always use array format:>>> from libtmux._internal.sparse_array import SparseArray>>> hooks_output = io.StringIO(r''' ... session-renamed[0] display-message 'renamed' ... session-renamed[5] refresh-client ... pane-focus-in[0] run-shell 'echo focus' ... ''') >>> hooks_exploded = explode_arrays( ... parse_options_to_dict(hooks_output), ... force_array=True, ... )Each hook becomes a SparseArray preserving indices:
>>> isinstance(hooks_exploded["session-renamed"], SparseArray) True >>> hooks_exploded["session-renamed"][0] "display-message 'renamed'" >>> hooks_exploded["session-renamed"][5] 'refresh-client' >>> sorted(hooks_exploded["session-renamed"].keys()) [0, 5]
- explode_complex ( _dict : ExplodedUntypedOptionsDict ) ExplodedComplexUntypedOptionsDict
-
Explode arrayed option's complex values.
Examples
>>> import io>>> explode_complex(explode_arrays(parse_options_to_dict(io.StringIO(r''' ... terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus ... terminal-features[5] screen*:title ... ''')))) {'terminal-features': {'xterm*': ['clipboard', 'ccolour', 'cstyle', 'focus'], 'screen*': ['title']}}>>> explode_complex(explode_arrays(parse_options_to_dict(io.StringIO(r''' ... terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus ... terminal-features[5] screen*:title ... ''')))) == { ... "terminal-features": {"xterm*": ["clipboard", "ccolour", "cstyle", "focus"], ... "screen*": ["title"]}} True>>> explode_complex(explode_arrays(parse_options_to_dict(io.StringIO(r''' ... command-alias[0] split-pane=split-window ... command-alias[1] splitp=split-window ... command-alias[2] "server-info=show-messages -JT" ... ''')))) == { ... "command-alias": {"split-pane": "split-window", ... "splitp": "split-window", ... "server-info": "show-messages -JT"}} True>>> explode_complex(explode_arrays({"terminal-features": {0: "xterm*:clipboard:ccolour:cstyle:focus", ... 1: "screen*:title"}})) {'terminal-features': {0: 'xterm*:clipboard:ccolour:cstyle:focus', 1: 'screen*:title'}}>>> explode_complex(explode_arrays({"terminal-features": {0: "xterm*:clipboard:ccolour:cstyle:focus", ... 8: "screen*:title"}})) == SparseArray({'terminal-features': {0: ... 'xterm*:clipboard:ccolour:cstyle:focus', 8: 'screen*:title'}}) True>>> explode_complex(explode_arrays(parse_options_to_dict(io.StringIO(r''' ... terminal-overrides[0] xterm-256color:Tc ... terminal-overrides[1] *:U8=0 ... ''')))) == { ... "terminal-overrides": {"xterm-256color": {"Tc": None}, ... "*": {"U8": 0}}} True>>> explode_complex(explode_arrays(parse_options_to_dict(io.StringIO(r''' ... user-keys[100] "\e[test" ... user-keys[6] "\e\n" ... user-keys[0] "\e[5;30012~" ... ''')))) == { ... "user-keys": {0: "\\e[5;30012~", ... 6: "\\e\\n", ... 100: "\\e[test"}} True>>> explode_complex(explode_arrays(parse_options_to_dict(io.StringIO(r''' ... status-format[0] "#[align=left range=left #{E:status-left-style}]#[push-default]#{T;=/#{status-left-length}:status-left}#[pop-default]#[norange default]#[list=on align=#{status-justify}]#[list=left-marker]<#[list=right-marker]>#[list=on]#{W:#[range=window|#{window_index} #{E:window-status-style}#{?#{&&:#{window_last_flag},#{!=:#{E:window-status-last-style},default}}, #{E:window-status-last-style},}#{?#{&&:#{window_bell_flag},#{!=:#{E:window-status-bell-style},default}}, #{E:window-status-bell-style},#{?#{&&:#{||:#{window_activity_flag},#{window_silence_flag}},#{!=:#{E:window-status-activity-style},default}}, #{E:window-status-activity-style},}}]#[push-default]#{T:window-status-format}#[pop-default]#[norange default]#{?window_end_flag,,#{window-status-separator}},#[range=window|#{window_index} list=focus #{?#{!=:#{E:window-status-current-style},default},#{E:window-status-current-style},#{E:window-status-style}}#{?#{&&:#{window_last_flag},#{!=:#{E:window-status-last-style},default}}, #{E:window-status-last-style},}#{?#{&&:#{window_bell_flag},#{!=:#{E:window-status-bell-style},default}}, #{E:window-status-bell-style},#{?#{&&:#{||:#{window_activity_flag},#{window_silence_flag}},#{!=:#{E:window-status-activity-style},default}}, #{E:window-status-activity-style},}}]#[push-default]#{T:window-status-current-format}#[pop-default]#[norange list=on default]#{?window_end_flag,,#{window-status-separator}}}#[nolist align=right range=right #{E:status-right-style}]#[push-default]#{T;=/#{status-right-length}:status-right}#[pop-default]#[norange default]" ... status-format[1] "#[align=centre]#{P:#{?pane_active,#[reverse],}#{pane_index}[#{pane_width}x#{pane_height}]#[default] }" ... ''')))) == { ... "status-format": {0: "#[align=left range=left #{E:status-left-style}]#[push-default]#{T;=/#{status-left-length}:status-left}#[pop-default]#[norange default]#[list=on align=#{status-justify}]#[list=left-marker]<#[list=right-marker]>#[list=on]#{W:#[range=window|#{window_index} #{E:window-status-style}#{?#{&&:#{window_last_flag},#{!=:#{E:window-status-last-style},default}}, #{E:window-status-last-style},}#{?#{&&:#{window_bell_flag},#{!=:#{E:window-status-bell-style},default}}, #{E:window-status-bell-style},#{?#{&&:#{||:#{window_activity_flag},#{window_silence_flag}},#{!=:#{E:window-status-activity-style},default}}, #{E:window-status-activity-style},}}]#[push-default]#{T:window-status-format}#[pop-default]#[norange default]#{?window_end_flag,,#{window-status-separator}},#[range=window|#{window_index} list=focus #{?#{!=:#{E:window-status-current-style},default},#{E:window-status-current-style},#{E:window-status-style}}#{?#{&&:#{window_last_flag},#{!=:#{E:window-status-last-style},default}}, #{E:window-status-last-style},}#{?#{&&:#{window_bell_flag},#{!=:#{E:window-status-bell-style},default}}, #{E:window-status-bell-style},#{?#{&&:#{||:#{window_activity_flag},#{window_silence_flag}},#{!=:#{E:window-status-activity-style},default}}, #{E:window-status-activity-style},}}]#[push-default]#{T:window-status-current-format}#[pop-default]#[norange list=on default]#{?window_end_flag,,#{window-status-separator}}}#[nolist align=right range=right #{E:status-right-style}]#[push-default]#{T;=/#{status-right-length}:status-right}#[pop-default]#[norange default]", ... 1: "#[align=centre]#{P:#{?pane_active,#[reverse],}#{pane_index}[#{pane_width}x#{pane_height}]#[default] }", ... }} True
-
Fetch the single
list-*row whose *obj_key* equals *obj_id*.A listing enumerates winlinks, so a window linked into one session at two indexes matches twice.
_best_winlinkthen picks the row tmux itself would act on, rather than whichever sorted last.Examples
>>> from libtmux.neo import fetch_obj >>> fetch_obj( ... server=pane.server, ... obj_key="pane_id", ... obj_id=pane.pane_id, ... list_cmd="list-panes", ... list_extra_args=("-t", pane.pane_id), ... )["pane_id"] == pane.pane_id TrueA pane that does not exist on a live server is a
TmuxObjectDoesNotExist, not a bare tmux error:>>> from libtmux import exc >>> try: ... fetch_obj( ... server=pane.server, ... obj_key="pane_id", ... obj_id="%99999", ... list_cmd="list-panes", ... list_extra_args=("-t", "%99999"), ... ) ... except exc.TmuxObjectDoesNotExist as e: ... print(e) Could not find pane_id=%99999 for list-panes ('-t', '%99999')- Parameters
-
-
server ( Server ) – The tmux server to query.
-
obj_key ( str ) – Identity field to match, e.g.
"pane_id". -
obj_id ( str ) – Value the identity field must equal, e.g.
"%3". -
list_cmd ( ListCmd ) – tmux list subcommand to run.
-
list_extra_args ( ListExtraArgs ) – Extra arguments appended verbatim to the tmux command, e.g.
("-t", "%3")to scope the listing to one object's parent.
-
- Returns
-
OutputRaw The matching row, as a dict of tmux format fields.
- Raises
-
-
TmuxObjectDoesNotExist – When the object does not exist -- whether tmux said so on stderr (
can't find pane: %99, for a-t-scoped listing) or the object simply never appeared in the rows. -
LibTmuxException – For every other tmux failure, notably an unreachable server.
-
- fetch_objs ( server : Server , list_cmd : ListCmd , list_extra_args : ListExtraArgs = None , filter : str | None = None , # noqa: A002 ) OutputsRaw
-
Fetch a listing of raw data from a tmux command.
Runs a tmux list command (e.g.
list-sessions) with the format string fromget_output_formatand parses each line of output into a dict.Examples
>>> from libtmux.neo import fetch_objs >>> objs = fetch_objs(server=server, list_cmd="list-sessions") >>> isinstance(objs, list) True >>> isinstance(objs[0], dict) True >>> 'session_id' in objs[0] True- Parameters
-
-
server ( Server ) – The tmux server to query.
-
list_cmd ( ListCmd ) – The tmux list command to run, e.g.
"list-sessions","list-windows", or"list-panes". -
list_extra_args ( ListExtraArgs ) – Extra arguments appended to the tmux command (e.g.
("-a",)for all windows/panes, or["-t", session_id]to filter). -
filter ( str | None ) – Filter expression evaluated by tmux (
-fflag). tmux omits rows whose expanded expression is false before libtmux parses the result. tmux silently expands a malformed filter (unclosed#{...}, unknown format token) to empty, which is treated as false — every row is suppressed and no stderr is emitted. A bad filter is indistinguishable from "filter matched nothing"; verify the expression against the FORMATS section oftmux(1). See native-filtering for the typed wrappers that share this caveat. Warning: added 0.57
-
- Returns
-
OutputsRaw A list of dicts, each mapping tmux format field names to their non-empty string values.
- Raises
-
-
LibTmuxException – If the tmux command writes to stderr.
-
- get_libtmux_version ( ) LooseVersion
-
Return libtmux version is a PEP386 compliant format.
- Returns
-
distutils.version.LooseVersion libtmux version
-
Return field names and tmux format string filtered by scope and version.
Only emits tokens whose scope is reachable from *list_cmd* (per
SCOPES_BY_LIST_CMD) and whose minimum tmux version (perFIELD_VERSION) is at or below *tmux_version*. Runtime-only tokens (mouse_*,cursor_*, popups) are excluded from everylist-*template — they only resolve in event-time format contexts.Examples
>>> from libtmux.neo import get_output_format >>> fields, fmt = get_output_format("list-sessions", "3.6a") >>> 'session_id' in fields True >>> 'pane_id' in fields # active pane for the listed session True >>> 'client_name' in fields # upward not allowed False >>> 'server' in fields FalsePane scope picks up window and session tokens too:
>>> fields, _ = get_output_format("list-panes", "3.6a") >>> all(t in fields for t in ('pane_id', 'window_id', 'session_id')) Truelist-clientsadds fields for the attached client:>>> fields, _ = get_output_format("list-clients", "3.6a") >>> 'client_name' in fields True >>> 'pane_id' in fields True- Parameters
-
-
list_cmd ( str ) – The tmux list subcommand the format string is being built for. Determines which token scopes are reachable.
-
tmux_version ( str ) – The live tmux version. Used to gate post-3.2a tokens. Defaults to
"3.2a"(the project's minimum) for safe fallback when the caller can't yet detect the version.
-
- Returns
-
tuple[tuple[str, ...], str] A tuple of (field_names, tmux_format_string) restricted to tokens the given *list_cmd* and *tmux_version* can resolve.
- get_version ( tmux_bin : str | None = None ) 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
-openbsdappended to the latest version, e.g.2.4-openbsd.- Parameters
-
-
tmux_bin ( str | None ) – Path to tmux binary. If *None*, uses the system tmux from
shutil.which.
-
- Returns
-
distutils.version.LooseVersiontmux version according to *tmux_bin* if provided, otherwise the system tmux fromshutil.which
-
Return the tmux version string verbatim, preserving letter suffixes.
get_versionnormalizes point releases for numeric comparison ("3.7a"becomesLooseVersion("3.7")). This helper keeps the raw suffix, so callers can distinguish patch releases whose behavior differs -- for example the tmux 3.7 break-pane crash, reverted in 3.7a.Examples
>>> isinstance(get_version_str(), str) True
- handle_option_error ( error : str ) type[exc.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. See https://github.com/tmux/tmux/blob/3.0/cmd-show-options.c.
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
exc.OptionError. So to catch any option error, useexcept exc.OptionError.Examples
>>> result = server.cmd( ... 'set-option', ... 'unknown-option-name', ... )>>> bool(isinstance(result.stderr, list) and len(result.stderr)) True>>> import pytest >>> from libtmux import exc>>> with pytest.raises(exc.OptionError): ... handle_option_error(result.stderr[0])- Parameters
-
-
error ( str ) – Error response from subprocess call.
-
- Raises
-
Return True if tmux version greater than minimum.
-
Return True if tmux version greater or equal to minimum.
-
Return True if tmux version less than minimum.
-
Return True if tmux version less or equal to minimum.
-
-
Return True if tmux meets version requirement. Version >= 3.2a.
- Parameters
- Returns
-
bool True if tmux meets minimum required version.
- Raises
-
-
libtmux.exc.VersionTooLow – tmux version below minimum required for libtmux
-
-
Return True if tmux version installed.
- home_path ( tmp_path_factory : pytest.TempPathFactory ) pathlib.Path
-
Temporary
/home/path.
-
Return default username to set for user_path fixture.
- is_sparse_array_list ( items : ExplodedComplexUntypedOptionsDict ) TypeGuard[HookArray]
-
Fetch values in objects and keys, supported nested data.
**With dictionaries**:
>>> keygetter({ "food": { "breakfast": "cereal" } }, "food") {'breakfast': 'cereal'}
>>> keygetter({ "food": { "breakfast": "cereal" } }, "food__breakfast") 'cereal'
**With objects**:
>>> from typing import List, Optional >>> from dataclasses import dataclass, field
>>> @dataclass() ... class Food: ... fruit: List[str] = field(default_factory=list) ... breakfast: Optional[str] = None
>>> @dataclass() ... class Restaurant: ... place: str ... city: str ... state: str ... food: Food = field(default_factory=Food)
>>> restaurant = Restaurant( ... place="Largo", ... city="Tampa", ... state="Florida", ... food=Food( ... fruit=["banana", "orange"], breakfast="cereal" ... ) ... )
>>> restaurant Restaurant(place='Largo', city='Tampa', state='Florida', food=Food(fruit=['banana', 'orange'], breakfast='cereal'))
>>> keygetter(restaurant, "food") Food(fruit=['banana', 'orange'], breakfast='cereal')
>>> keygetter(restaurant, "food__breakfast") 'cereal'
-
Return the pane id recorded in
$TMUX_PANE.The
%sigil is load-bearing: libtmux passes this id straight to tmux as a-ttarget, and tmux'scmd_findroutes a target to its pane slot *by sigil*. A sigil-less value would be matched against session names instead, silently resolving to the wrong object.Examples
>>> from libtmux._internal.env import pane_id_from_env >>> pane_id_from_env({"TMUX_PANE": "%3"}) '%3'>>> pane_id_from_env({}) Traceback (most recent call last): ... libtmux.exc.NotInsideTmux: Not inside a tmux pane: $TMUX_PANE is unset or empty>>> pane_id_from_env({"TMUX_PANE": "3"}) Traceback (most recent call last): ... libtmux.exc.NotInsideTmux: Not inside a tmux pane: $TMUX_PANE is not a pane id...- Parameters
-
-
env ( t.Mapping[str, str] | None ) – Environment to read. Defaults to
os.environ.
-
- Returns
-
str The pane id, e.g.
"%3". - Raises
-
-
NotInsideTmux – When
$TMUX_PANEis unset, empty, or is not a%-prefixed id.
-
-
Parse the given version string.
Examples
>>> parse('1.0.dev1') <Version('1.0.dev1')>- Raises
-
-
InvalidVersion – When the version string is not a valid version.
-
-
-
Check if field lookup key, e.g. "my__path__contains" has comparator, return val.
If comparator not used or value not found, return None.
>>> parse_lookup({ "food": "red apple" }, "food__istartswith", "__istartswith") 'red apple'
It can also look up objects:
>>> from dataclasses import dataclass
>>> @dataclass() ... class Inventory: ... food: str
>>> item = Inventory(food="red apple")
>>> item Inventory(food='red apple')
>>> parse_lookup(item, "food__istartswith", "__istartswith") 'red apple'
- parse_options_to_dict ( stdout : t.IO[str] ) UntypedOptionsDict
-
Process subprocess.stdout options or hook output to flat, naive, untyped dict.
Does not explode arrays or deep values.
Examples
>>> import io>>> raw_options = io.StringIO("status-keys vi") >>> parse_options_to_dict(raw_options) == {"status-keys": "vi"} True>>> int_options = io.StringIO("message-limit 50") >>> parse_options_to_dict(int_options) == {"message-limit": "50"} True>>> empty_option = io.StringIO("user-keys") >>> parse_options_to_dict(empty_option) == {"user-keys": None} True>>> array_option = io.StringIO("command-alias[0] split-pane=split-window") >>> parse_options_to_dict(array_option) == { ... "command-alias[0]": "split-pane=split-window"} True>>> array_option = io.StringIO("command-alias[40] split-pane=split-window") >>> parse_options_to_dict(array_option) == { ... "command-alias[40]": "split-pane=split-window"} True>>> many_options = io.StringIO(r'''status-keys ... command-alias[0] split-pane=split-window ... ''') >>> parse_options_to_dict(many_options) == { ... "command-alias[0]": "split-pane=split-window", ... "status-keys": None,} True>>> many_more_options = io.StringIO(r''' ... terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus ... terminal-features[1] screen*:title ... ''') >>> parse_options_to_dict(many_more_options) == { ... "terminal-features[0]": "xterm*:clipboard:ccolour:cstyle:focus", ... "terminal-features[1]": "screen*:title",} True>>> quoted_option = io.StringIO(r''' ... command-alias[0] "choose-session=choose-tree -s" ... ''') >>> parse_options_to_dict(quoted_option) == { ... "command-alias[0]": "choose-session=choose-tree -s", ... } True
-
Parse a tmux
-Fline into a dict keyed by Obj field name.The (*list_cmd*, *tmux_version*) pair must match what was passed to
get_output_formatwhen the-Ftemplate was built — otherwise the field order won't line up with the split values.Examples
>>> from libtmux.neo import get_output_format, parse_output >>> from libtmux.formats import FORMAT_SEPARATOR >>> fields, fmt = get_output_format("list-sessions", "3.6a") >>> values = [''] * len(fields) >>> values[fields.index('session_id')] = '$1' >>> result = parse_output( ... FORMAT_SEPARATOR.join(values) + FORMAT_SEPARATOR, ... list_cmd="list-sessions", ... tmux_version="3.6a", ... ) >>> result['session_id'] '$1' >>> 'pane_id' in result False- Parameters
-
-
output ( str ) – Raw tmux output line produced with a template from
get_output_format. -
list_cmd ( str ) – Same value passed to
get_output_format. -
tmux_version ( str ) – Same value passed to
get_output_format.
-
- Returns
-
OutputRaw A dict mapping field names to non-empty string values.
-
Raise
LibTmuxExceptiontagged with the tmux subcommand on stderr.Centralizes the
if proc.stderr: raise exc.LibTmuxException(proc.stderr)pattern scattered across the wrappers. Tags the exception with the originating tmux subcommand so downstream consumers (e.g. libtmux-mcp'shandle_tool_errors) keep the "which tmux command failed" context.Examples
>>> from libtmux.common import raise_if_stderr >>> from libtmux import exc >>> proc = session.cmd("display-message", "-p", "#{session_id}") >>> raise_if_stderr(proc, "display-message") # no stderr → no raise- Parameters
-
-
proc ( tmux_cmd ) – Result of a
Server.cmd/Session.cmd/ etc. call. -
subcommand ( str ) – The tmux subcommand the wrapper invoked, e.g.
"last-window","swap-pane". Surfaces instr(exc)as a"<subcommand>: …"prefix.
-
- Raises
-
-
LibTmuxException – When
proc.stderris non-empty.
-
- reraise ( tp : t.Type[BaseException] , value : BaseException , tb : types.TracebackType ) t.NoReturn
-
Return *env*, defaulting to the live process environment.
Examples
>>> from libtmux._internal.env import resolve_env >>> resolve_env({"TMUX_PANE": "%1"}) {'TMUX_PANE': '%1'}>>> resolve_env() is os.environ True- Parameters
-
-
env ( t.Mapping[str, str] | None ) – Environment to read. Defaults to
os.environ.
-
- Returns
-
typing.MappingThe mapping to read tmux variables from.
- server ( request : pytest.FixtureRequest , monkeypatch : pytest.MonkeyPatch , config_file : pathlib.Path ) Server
-
Return new, temporary
libtmux.Server.>>> from libtmux.server import Server
>>> def test_example(server: Server) -> None: ... assert isinstance(server, Server) ... session = server.new_session('my session') ... assert len(server.sessions) == 1 ... assert [session.name.startswith('my') for session in server.sessions]
.. :: >>> locals().keys() dict_keys(...)
>>> source = ''.join([e.source for e in request._pyfuncitem.dtest.examples][:3]) >>> pytester = request.getfixturevalue('pytester')
>>> pytester.makepyfile(**{'whatever.py': source}) PosixPath(...)
>>> result = pytester.runpytest('whatever.py', '--disable-warnings') ===...
>>> result.assert_outcomes(passed=1)
-
Return new, temporary
libtmux.Session.>>> from libtmux.session import Session
>>> def test_example(session: "Session") -> None: ... assert isinstance(session.name, str) ... assert session.name.startswith('libtmux_') ... window = session.new_window(window_name='new one') ... assert window.name == 'new one'
.. :: >>> locals().keys() dict_keys(...)
>>> source = ''.join([e.source for e in request._pyfuncitem.dtest.examples][:3]) >>> pytester = request.getfixturevalue('pytester')
>>> pytester.makepyfile(**{'whatever.py': source}) PosixPath(...)
>>> result = pytester.runpytest('whatever.py', '--disable-warnings') ===...
>>> result.assert_outcomes(passed=1)
-
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
- Raises
-
-
exc.BadSessionName – Invalid session name.
-
-
Return default session creation parameters.
>>> import pytest >>> from libtmux.session import Session
>>> @pytest.fixture ... def session_params(session_params): ... return { ... 'x': 800, ... 'y': 600, ... }
>>> def test_example(session: "Session") -> None: ... assert isinstance(session.name, str) ... assert session.name.startswith('libtmux_') ... window = session.new_window(window_name='new one') ... assert window.name == 'new one'
.. :: >>> locals().keys() dict_keys(...)
>>> source = ''.join([e.source for e in request._pyfuncitem.dtest.examples][:4]) >>> pytester = request.getfixturevalue('pytester')
>>> pytester.makepyfile(**{'whatever.py': source}) PosixPath(...)
>>> result = pytester.runpytest('whatever.py', '--disable-warnings') ===...
>>> result.assert_outcomes(passed=1)
-
Return the tmux socket path recorded in
$TMUX.$TMUXis"<socket_path>,<server_pid>,<session_id>". The pid and session id are integers, so any comma in the value belongs to the socket path -- split from the *right*.The pid and session id are deliberately discarded: both are frozen at pane spawn, and the session id goes stale as soon as the pane's window is moved between sessions.
Examples
>>> from libtmux._internal.env import socket_path_from_env >>> socket_path_from_env({"TMUX": "/tmp/tmux-1000/default,84215,0"}) '/tmp/tmux-1000/default'A comma in the socket path is safe, because the split runs from the right:
>>> socket_path_from_env({"TMUX": "/tmp/od,d/sock,84215,3"}) '/tmp/od,d/sock'Outside tmux there is nothing to read:
>>> socket_path_from_env({}) Traceback (most recent call last): ... libtmux.exc.NotInsideTmux: Not inside a tmux pane: $TMUX is unset or empty- Parameters
-
-
env ( t.Mapping[str, str] | None ) – Environment to read. Defaults to
os.environ.
-
- Returns
-
str Path of the tmux server's socket.
- Raises
-
-
NotInsideTmux – When
$TMUXis unset, empty, or not shaped like tmux's triple.
-
-
Create a temporary tmux server that cleans up after itself.
This is similar to the server pytest fixture, but can be used outside of pytest. The server will be killed when the test completes.
Examples
>>> server = Server() # Create server instance >>> server.new_session() Session($... ...) >>> server.is_alive() True >>> # Each call creates a new server with unique socket >>> server2 = Server() >>> server2.socket_name != server.socket_name True
- user_path ( home_path : pathlib.Path , home_user_name : str ) pathlib.Path
-
Ensure and return temporary user directory.
Note: You will need to set the home directory, see set_home.
- zshrc ( user_path : pathlib.Path ) pathlib.Path
-
Suppress ZSH default message.
Needs a startup file .zshenv, .zprofile, .zshrc, .zlogin.