Servers¶
Identified by socket path and socket name
May have >1 servers running of tmux at the same time.
Contain Sessions (which contain Windows, which contain Panes)
tmux initializes a server automatically on first running (e.g. executing tmux)
Bases:
EnvironmentMixin,OptionsMixin,HooksMixintmux(1) Server [server_manual].
Server.sessions[Session, …]Session.windows[Window, …]Window.panes[Pane, …]
When instantiated stores information on live, running tmux server.
Examples
>>> server Server(socket_name=libtmux_test...)
>>> server.sessions [Session($1 ...)]
>>> server.sessions[0].windows [Window(@1 1:..., Session($1 ...))]
>>> server.sessions[0].active_window Window(@1 1:..., Session($1 ...))
>>> server.sessions[0].active_pane Pane(%1 Window(@1 1:..., Session($1 ...)))
The server can be used as a context manager to ensure proper cleanup:
>>> with Server() as server: ... session = server.new_session() ... # Do work with the session ... # Server will be killed automatically when exiting the context
References
[server_manual]- CLIENTS AND SESSIONS. openbsd manpage for TMUX(1)
“The tmux server manages clients, sessions, windows and panes. Clients are attached to sessions to interact with them, either when they are created with the new-session command, or later with the attach-session command. Each session has one or more windows linked into it. Windows may be linked to multiple sessions and are made up of one or more panes, each of which contains a pseudo terminal.”
https://man.openbsd.org/tmux.1#CLIENTS_AND_SESSIONS. Accessed April 1st, 2018.
Custom path to tmux binary. Falls back to
shutil.which("tmux").
Return True if tmux server alive.
>>> tmux = Server(socket_name="no_exist") >>> assert not tmux.is_alive()
- Return type:
Raise if server not connected.
- Raises:
exc.TmuxCommandNotFound– When the tmux binary cannot be found or executed.subprocess.CalledProcessError– When the tmux server is not running (non-zero exit fromlist-sessions).>>> tmux = Server(socket_name="no_exist") –>>> try:–...
tmux.raise_if_dead() –...
except Exception as e:–...
print(type(e)) –<class 'subprocess.CalledProcessError'>–
- Return type:
Execute tmux command respective of socket name and file, return output.
Examples
>>> server.cmd('display-message', 'hi') <libtmux.common.tmux_cmd object at ...>
New session:
>>> server.cmd('new-session', '-d', '-P', '-F#{session_id}').stdout[0] '$2'
>>> session.cmd('new-window', '-P').stdout[0] 'libtmux...:2.0'
Output of tmux -L … new-window -P -F#{window_id} to a Window object:
>>> Window.from_window_id(window_id=session.cmd( ... 'new-window', '-P', '-F#{window_id}').stdout[0], server=session.server) Window(@4 3:..., Session($1 libtmux_...))
Create a pane from a window:
>>> window.cmd('split-window', '-P', '-F#{pane_id}').stdout[0] '%5'
Output of tmux -L … split-window -P -F#{pane_id} to a Pane object:
>>> Pane.from_pane_id(pane_id=window.cmd( ... 'split-window', '-P', '-F#{pane_id}').stdout[0], server=window.server) Pane(%... Window(@... ...:..., Session($1 libtmux_...)))
- Parameters:
- Return type:
Notes
Changed in version 0.8: Renamed from
.tmuxto.cmd.
- Returns:
Sessions that are attached.
- Return type:
list[
Session]
Return True if session exists.
- Parameters:
- Raises:
- Return type:
Kill tmux server.
>>> svr = Server(socket_name="testing") >>> svr Server(socket_name=testing)
>>> svr.new_session() Session(...)
>>> svr.is_alive() True
>>> svr.kill()
>>> svr.is_alive() False
- Return type:
Kill tmux session.
- Parameters:
target_session (
str,optional) – target_session: str. note this acceptsfnmatch(3). ‘asdf’ will kill ‘asdfasd’.- Return type:
- Raises:
Execute a shell command via
$ tmux run-shell.- Parameters:
command (
str) – Shell command to execute.background (
bool,optional) – Run in background (-bflag).delay (
str,optional) – Delay before execution (-dflag).as_tmux_command (
bool,optional) – Parse argument as a tmux command instead of a shell command (-Cflag).target_pane (
str,optional) – Target pane for output (-tflag).cwd (
str or PathLike, optional) –Start directory for the shell command (
-cflag). When omitted, tmux uses the target client’s current working directory. Requires tmux 3.4+; on older tmux a warning is emitted and the kwarg is ignored.Note: tmux’s
-cis a start directory, not subprocess semantics. Ifchdir(cwd)fails, tmux falls back to the user’s home directory, then to/, rather than raising — unlike Python’ssubprocess.Popen(cwd=)which errors on a failed chdir.Added in version 0.57.
show_stderr (
bool,optional) –Combine the command’s stderr into the captured output stream (
-Eflag, maps toJOB_SHOWSTDERR). Requires tmux 3.6+; on older tmux a warning is emitted and the kwarg is ignored.Added in version 0.57.
- Returns:
Stdout lines, or None when background is True. Empty list on tmux 3.3a/3.4 (upstream stdout passthrough was broken until 3.5).
- Return type:
Examples
>>> result = server.run_shell('true') >>> isinstance(result, list) True
Wait for, signal, or lock a channel via
$ tmux wait-for.Examples
>>> server.new_session(session_name='wait_test') Session(...) >>> server.wait_for('test_channel', set_flag=True)
Bind a key to a command via
$ tmux bind-key.- Parameters:
- Return type:
Examples
>>> server.bind_key('F12', 'display-message test', key_table='root') >>> server.unbind_key('F12', key_table='root')
Unbind a key via
$ tmux unbind-key.Examples
>>> server.bind_key('F11', 'display-message test', key_table='root') >>> server.unbind_key('F11', key_table='root')
Lock the tmux server via
$ tmux lock-server.Requires an attached client.
>>> with control_mode() as ctl: ... server.lock_server()
- Return type:
Manage server access control via
$ tmux server-access.Requires tmux 3.3+ (introduced in 3.3).
- Parameters:
allow (
str,optional) – Allow a user (-aflag).deny (
str,optional) – Deny a user (-dflag).list_access (
bool,optional) – List access rules (-lflag).read_only (
bool,optional) – Force the user to attach read-only (-rflag). Implies allow if the user is not already in the ACL. Mutually exclusive with write — tmux rejects-r -w.write (
bool,optional) – Allow the user to attach read-write (-wflag). Implies allow if the user is not already in the ACL. Mutually exclusive with read_only.
- Returns:
Access list when list_access is True, None otherwise.
- Return type:
Examples
>>> from libtmux.common import has_gte_version >>> if has_gte_version("3.3"): ... result = server.server_access(list_access=True) ... assert isinstance(result, list)
Refresh a client’s display via
$ tmux refresh-client.Requires an attached client.
Examples
>>> with control_mode() as ctl: ... server.refresh_client()
Suspend a client via
$ tmux suspend-client.Requires an attached client.
Examples
>>> with control_mode() as ctl: ... server.suspend_client()
Lock a client via
$ tmux lock-client.Requires an attached client.
Examples
>>> with control_mode() as ctl: ... server.lock_client()
Detach a specific client via
$ tmux detach-client.Maps to
$ tmux detach-client [-t <target_client>]. tmux resolves-tover the global client list (seecmd-find.c); the named client may be attached to any session, so this method lives onServerrather thanSession.See also
Session.detach_client()detach every client attached to a session (
-sflag).detach_all_clients()detach every client on the server (
-aflag).
Examples
>>> with control_mode() as ctl: ... server.detach_client(target_client=ctl.client_name)
Detach every client on this server via
$ tmux detach-client -a.tmux’s
-aalways preserves one client; when keep_client is omitted, the most-recently-active client survives.See also
Session.detach_client()detach every client attached to a session (
-sflag).detach_client()detach a single named client (
-tflag).
Examples
>>> with control_mode() as ctl: ... server.detach_all_clients(keep_client=ctl.client_name)
Run a command after confirmation via
$ tmux confirm-before.Always uses
-b(background) to avoid blocking the command queue. Usesend-keys -K -c <client>to provide the confirmation key.Requires tmux 3.3+ for
-bflag support.- Parameters:
command (
str) – Tmux command to run after confirmation.prompt (
str,optional) – Custom prompt text (-pflag).confirm_key (
str,optional) – Key to accept as confirmation (-cflag). Default isy. Requires tmux 3.4+.default_yes (
bool,optional) – Make Enter default to yes (-yflag). Requires tmux 3.4+.target_client (
str,optional) – Target client (-tflag).
- Return type:
Examples
Interactive confirmation requires tmux 3.4+; the wrapper itself works on 3.3+ but the
send-keys -K -c <client>round-trip used here is unreliable on 3.3a:>>> from libtmux.common import has_gte_version >>> if has_gte_version("3.4"): ... with control_mode() as ctl: ... server.confirm_before( ... 'set -g @cf_test yes', ... target_client=ctl.client_name, ... ) ... _ = server.cmd('send-keys', '-K', '-c', ctl.client_name, 'y') ... result = server.cmd('show-options', '-gv', '@cf_test').stdout[0] ... else: ... result = 'yes' >>> result 'yes'
Open a command prompt via
$ tmux command-prompt.Always uses
-b(background) to avoid blocking the command queue. Usesend-keys -K -c <client>to type into the prompt and submit.Requires tmux 3.3+ for
-bflag support.- Parameters:
template (
str) – Tmux command template. Use%1,%2for prompt values.prompt (
str,optional) – Custom prompt text (-pflag). Commas separate multiple prompts.inputs (
str,optional) – Pre-fill prompt input (-Iflag). Commas separate multiple.target_client (
str,optional) – Target client (-tflag).one_key (
bool,optional) – Accept only one key press (-1flag).key_only (
bool,optional) – Only accept key presses, not text (-kflag).on_input_change (
bool,optional) – Run template on each keystroke (-iflag).numeric (
bool,optional) – Accept only numeric input (-Nflag).prompt_type (
str,optional) – Prompt type (-Tflag).expand_format (
bool,optional) – Pass the template throughargs_make_commands_prepare(-Fflag) so format strings expand. Requires tmux 3.3+.literal (
bool,optional) – Disable splitting prompt on commas — treat it as a single prompt (-lflag). Requires tmux 3.6+.bspace_exit (
bool,optional) – Close the prompt when the user empties it with backspace (-eflag,PROMPT_BSPACE_EXIT). Requires tmux 3.7+ (upstream master).
- Return type:
Examples
Interactive prompts require tmux 3.4+; the wrapper itself works on 3.3+ but the
send-keys -K -c <client>round-trip used here is unreliable on 3.3a:>>> from libtmux.common import has_gte_version >>> if has_gte_version("3.4"): ... with control_mode() as ctl: ... server.command_prompt( ... "set -g @cp_test '%1'", ... target_client=ctl.client_name, ... ) ... for key in ['h', 'i', 'Enter']: ... _ = server.cmd('send-keys', '-K', '-c', ctl.client_name, key) ... result = server.cmd('show-options', '-gv', '@cp_test').stdout[0] ... else: ... result = 'hi' >>> result 'hi'
Display a popup menu via
$ tmux display-menu.Requires a TTY-backed attached client. Control-mode clients have
tty.sy=0, which causesmenu_prepare()to return NULL. This method cannot be tested withControlMode.- Parameters:
*items (
str) – Menu items as positional args in tmux’sname key commandtriple format. Use empty strings for separators.title (
str,optional) – Menu title (-Tflag).target_pane (
str,optional) – Target pane for format expansion (-tflag).target_client (
str,optional) – Target client (-cflag).x (
int or str, optional) – Menu x position (-xflag).y (
int or str, optional) – Menu y position (-yflag).starting_choice (
int or str, optional) – Pre-selected item index (-Cflag). Use-for none. Requires tmux 3.4+.border_lines (
str,optional) – Border line style (-bflag). Requires tmux 3.4+.style (
str,optional) – Menu style (-sflag). Requires tmux 3.4+.border_style (
str,optional) – Border style (-Sflag). Requires tmux 3.4+.selected_style (
str,optional) – Style for the currently selected menu item (-Hflag). Requires tmux 3.4+.mouse (
bool,optional) – Always enable mouse handling in the menu (-Mflag). Requires tmux 3.5+.stay_open (
bool,optional) – Keep the menu open when the mouse is released (-Oflag). Requires tmux 3.2+.
- Return type:
Examples
Cannot run end-to-end (requires a TTY-backed client; see the
tty.sy=0note above). For broader coverage, seetests/test_server.py::test_display_menu_flags.>>> captured = [] >>> def fake_cmd(name, *args, **_kw): ... captured.append((name, args)) ... return type('R', (), {'stderr': [], 'stdout': []})() >>> monkeypatch.setattr(server, 'cmd', fake_cmd) >>> server.display_menu('First', '1', 'select-pane', title='menu') >>> captured[0][0] 'display-menu'
Start the tmux server via
$ tmux start-server.Usually not needed since the server starts automatically on first session creation.
>>> server.start_server()
- Return type:
Show server message log via
$ tmux show-messages.Without
-T/-J, tmux resolves the message log against a target client; if no client is attached and target_client is omitted, tmux raisesno current client. Provide target_client (e.g. viaControlMode) when running headless, or use terminals/jobs — those modes don’t require a client.- Parameters:
- Returns:
Server message log lines (or terminal/job summary when terminals/jobs is set).
- Return type:
Examples
>>> with control_mode() as ctl: ... result = server.show_messages(target_client=ctl.client_name) >>> isinstance(result, list) True
-
method
Display message at server scope via
$ tmux display-message.Like
Pane.display_message()but without-t <pane-id>injection. tmux’scmd-display-messageentry usesCMD_FIND_CANFAILso the target is optional; server-scoped format reads (#{version},#{socket_path},#{pid}) resolve without a specific pane handle.With no client attached and
target_clientomitted, the status-line path (get_text=False) issues ano current clientwarning. Useget_text=Truefor headless reads, or pair withControlMode.Notes
Stderr from tmux is reported via
warnings.warn(), not raised. tmux uses stderr for both genuine errors and informational messages, and the right escalation depends on tmux version and call shape. Callers that want to escalate to an exception can wrap the call inwarnings.catch_warnings()withfilterwarnings("error").Changed in version 0.57: Reports stderr via
warnings.warn()instead of raising.- Parameters:
cmd (
str) –Format string to display or evaluate (e.g.
"#{version}"). Pass""together withall_formats=Trueto dump every variable.Added in version 0.57.
get_text (
bool,optional) –Return tmux’s stdout instead of rendering to the status line (
-pflag).Added in version 0.57.
format_string (
str,optional) –Alternative format template (
-Fflag).Added in version 0.57.
all_formats (
bool,optional) –List all format variables (
-aflag).Added in version 0.57.
verbose (
bool,optional) –Show format variable types (
-vflag).Added in version 0.57.
no_expand (
bool,optional) –Output the literal string without format expansion (
-lflag). Requires tmux 3.4+.Added in version 0.57.
target_client (
str,optional) –Target client (
-cflag).Added in version 0.57.
delay (
int,optional) –Display time in milliseconds (
-dflag).Added in version 0.57.
notify (
bool,optional) –Do not wait for input (
-Nflag).Added in version 0.57.
- Returns:
Message output if
get_textis True, otherwiseNone.- Return type:
Examples
Read tmux version without needing a pane handle:
>>> result = server.display_message("#{version}", get_text=True) >>> isinstance(result, list) and len(result) == 1 True
Dump every format variable:
>>> result = server.display_message("", get_text=True, all_formats=True) >>> any("session_name=" in line for line in result) True
Show prompt history via
$ tmux show-prompt-history.Examples
>>> from libtmux.common import has_gte_version >>> if has_gte_version("3.3"): ... result = server.show_prompt_history() ... else: ... result = [] >>> isinstance(result, list) True
Clear prompt history via
$ tmux clear-prompt-history.Examples
>>> from libtmux.common import has_gte_version >>> if has_gte_version("3.3"): ... server.clear_prompt_history()
Set a paste buffer via
$ tmux set-buffer.Examples
>>> server.set_buffer('hello') >>> server.show_buffer() 'hello'
Save a paste buffer to a file via
$ tmux save-buffer.Examples
>>> import pathlib >>> server.set_buffer('save_me') >>> path = pathlib.Path(request.config.rootdir) / '..' / 'tmp_save.txt' >>> server.save_buffer(str(path))
Load a file into a paste buffer via
$ tmux load-buffer.Examples
>>> import pathlib >>> path = pathlib.Path(request.config.rootdir) / '..' / 'tmp_load.txt' >>> _ = path.write_text('loaded') >>> server.load_buffer(str(path), buffer_name='loaded_buf')
List paste buffers via
$ tmux list-buffers.Without arguments returns tmux’s default template (
name: N bytes: "sample") — kept for backward compatibility. Pass format_string to request a specific tmux format, or filter to have tmux return only matching buffers.- Parameters:
format_string (
str,optional) –Output template (
-Fflag). Example:"#{buffer_name}"for raw names only.Added in version 0.57.
filter (
str,optional) –Filter expression evaluated by tmux (
-fflag). Buffers for which the expanded expression is false are omitted. Example:"#{m:libtmux_mcp_*,#{buffer_name}}".Note: this kwarg shadows the Python builtin
filterby design — it mirrors tmux’s own flag name (-f filter) for grep-friendly symmetry between the wrapper and the tmux manual.Warning
tmux silently expands a malformed filter (unclosed
#{...}, unknown format token) to empty, which the filter treats as false — every row is suppressed and no stderr is emitted. A bad filter is indistinguishable from “filter matched nothing”; verify filter syntax against the FORMATS section oftmux(1).Added in version 0.57.
- Returns:
Raw output lines.
- Return type:
Examples
Default template (backward-compatible):
>>> server.set_buffer('buf_data') >>> result = server.list_buffers() >>> len(result) >= 1 True
Project just the names:
>>> server.set_buffer('hello', buffer_name='gap6_demo') >>> 'gap6_demo' in server.list_buffers(format_string='#{buffer_name}') True
Filter via tmux:
>>> matches = server.list_buffers( ... format_string='#{buffer_name}', ... filter='#{m:gap6_*,#{buffer_name}}', ... ) >>> 'gap6_demo' in matches True
Execute a tmux command conditionally via
$ tmux if-shell.- Parameters:
shell_command (
str) – Shell command whose exit status determines which tmux command runs.tmux_command (
str) – Tmux command to run if shell_command succeeds (exit 0).else_command (
str,optional) – Tmux command to run if shell_command fails (non-zero exit).background (
bool,optional) – Run the shell command in the background (-bflag).target_pane (
str,optional) – Target pane for format expansion (-tflag).
- Return type:
Examples
>>> server.if_shell('true', 'set -g @if_test yes') >>> server.cmd('show-options', '-gv', '@if_test').stdout[0] 'yes'
Source a tmux configuration file via
$ tmux source-file.Examples
>>> import pathlib >>> conf = pathlib.Path(request.config.rootdir) / '..' / 'tmp_src.conf' >>> _ = conf.write_text('set -g @test_source yes') >>> server.source_file(str(conf))
List connected clients via
$ tmux list-clients.Examples
>>> isinstance(server.list_clients(), list) True
Switch tmux client.
- Parameters:
target_session (
str) – name of the session. fnmatch(3) works.- Raises:
- Return type:
Attach tmux session.
- Parameters:
target_session (
str) – name of the session. fnmatch(3) works.- Raises:
- Return type:
Create new session, returns new
Session.Uses
-Pflag to print session info,-Ffor return formatting returns new Session object.$ tmux new-session -dwill create the session in the background$ tmux new-session -Adwill move to the session name if it already exists. todo: make an option to handle this.- Parameters:
session_name (
str,optional) –$ tmux new-session -s <session_name>
attach (
bool,optional) –create session in the foreground.
attach=Falseis equivalent to:$ tmux new-session -d
kill_session (
bool,optional) – Kill current session if$ tmux has-session. Useful for testing workspaces.start_directory (
str or PathLike, optional) – specifies the working directory in which the new session is created.window_name (
str,optional) –$ tmux new-session -n <window_name>
window_command (
str,optional) – execute a command on starting the session. The window will close when the command exits. NOTE: When this command exits the window will close. This feature is useful for long-running processes where the closing of the window upon completion is desired.x (
int|str,optional) – Force the specified width instead of the tmux default for a detached sessiony (
int|str,optional) – Force the specified height instead of the tmux default for a detached sessiondetach_others (
bool,optional) –Detach other clients from the session (
-Dflag).Added in version 0.56.
no_size (
bool,optional) –Do not set the initial window size (
-Xflag).Added in version 0.56.
client_flags (
str,optional) –Set client flags (
-fflag), e.g.no-output,read-only. Requires tmux 3.2+.Added in version 0.56.
args (
Any)kwargs (
Any)
- Return type:
- Raises:
Examples
Sessions can be created without a session name (0.14.2+):
>>> server.new_session() Session($2 2)
Creating them in succession will enumerate IDs (via tmux):
>>> server.new_session() Session($3 3)
With a session_name:
>>> server.new_session(session_name='my session') Session($4 my session)
Sessions contained in server.
Can be accessed via
.sessions.get()and.sessions.filter()Returns an empty
QueryListwhen tmux’slist-sessionsfails for any reason — no running daemon, a missing socket, a permission error, or a subprocess failure. To distinguish “no sessions” from “tmux unreachable”, callServer.is_alive()orServer.raise_if_dead().
Windows contained in server’s sessions.
Can be accessed via
.windows.get()and.windows.filter()
Panes contained in tmux server (across all windows in all sessions).
Can be accessed via
.panes.get()and.panes.filter()
Return value for the hook.
- Parameters:
hook (
str)global_ (
bool)scope (
OptionScope|_DefaultOptionScope|None)
- Raises:
- Return type:
Return option value for the target.
todo: test and return True/False for on/off string
- Parameters:
- Raises:
- Return type:
ConvertedValue|None
Examples
>>> import typing as t >>> from libtmux.common import tmux_cmd >>> from libtmux.constants import OptionScope
>>> class MyServer(OptionsMixin): ... socket_name = server.socket_name ... def cmd(self, cmd: str, *args: object): ... cmd_args: t.List[t.Union[str, int]] = [cmd] ... if self.socket_name: ... cmd_args.insert(0, f"-L{self.socket_name}") ... cmd_args.insert(0, "-f/dev/null") ... return tmux_cmd(*cmd_args, *args) ... ... default_option_scope = OptionScope.Server
>>> MyServer().cmd('new-session', '-d') <libtmux.common.tmux_cmd object at ...>
>>> MyServer()._show_option('exit-unattached', global_=True) False
Return raw option output for target.
- Parameters:
- Raises:
- Return type:
Examples
>>> import typing as t >>> from libtmux.common import tmux_cmd >>> from libtmux.constants import OptionScope
>>> class MyServer(OptionsMixin): ... socket_name = server.socket_name ... def cmd(self, cmd: str, *args: object): ... cmd_args: t.List[t.Union[str, int]] = [cmd] ... if self.socket_name: ... cmd_args.insert(0, f"-L{self.socket_name}") ... cmd_args.insert(0, "-f/dev/null") ... return tmux_cmd(*cmd_args, *args) ... ... default_option_scope = OptionScope.Server
>>> MyServer().cmd('new-session', '-d') <libtmux.common.tmux_cmd object at ...>
>>> MyServer()._show_option_raw('exit-unattached', global_=True) <libtmux.common.tmux_cmd object at ...>
>>> MyServer()._show_option_raw('exit-unattached', global_=True).stdout ['exit-unattached off']
>>> isinstance(MyServer()._show_option_raw('exit-unattached', global_=True).stdout, list) True
>>> isinstance(MyServer()._show_option_raw('exit-unattached', global_=True).stdout[0], str) True
Return a dict of options for the target.
Examples
>>> import typing as t >>> from libtmux.common import tmux_cmd >>> from libtmux.constants import OptionScope
>>> class MyServer(OptionsMixin): ... socket_name = server.socket_name ... def cmd(self, cmd: str, *args: object): ... cmd_args: t.List[t.Union[str, int]] = [cmd] ... if self.socket_name: ... cmd_args.insert(0, f"-L{self.socket_name}") ... cmd_args.insert(0, "-f/dev/null") ... return tmux_cmd(*cmd_args, *args) ... ... default_option_scope = OptionScope.Server
>>> MyServer()._show_options() {...}
Return dict of options for the target.
Examples
>>> import typing as t >>> from libtmux.common import tmux_cmd >>> from libtmux.constants import OptionScope
>>> class MyServer(OptionsMixin): ... socket_name = server.socket_name ... def cmd(self, cmd: str, *args: object): ... cmd_args: t.List[t.Union[str, int]] = [cmd] ... if self.socket_name: ... cmd_args.insert(0, f"-L{self.socket_name}") ... cmd_args.insert(0, "-f/dev/null") ... return tmux_cmd(*cmd_args, *args) ... ... default_option_scope = OptionScope.Server
>>> MyServer()._show_options_dict() {...}
>>> isinstance(MyServer()._show_options_dict(), dict) True
Return a dict of options for the target.
- Parameters:
g (
bool,optional) –Deprecated since version 0.50.0: Use
global_instead.quiet (
bool,optional) –Suppress errors silently (
-qflag).Added in version 0.56.
values_only (
bool,optional) –Return only option values without names (
-vflag).Added in version 0.56.
scope (
OptionScope|_DefaultOptionScope|None)
- Return type:
Examples
>>> import typing as t >>> from libtmux.common import tmux_cmd >>> from libtmux.constants import OptionScope
>>> class MyServer(OptionsMixin): ... socket_name = server.socket_name ... def cmd(self, cmd: str, *args: object): ... cmd_args: t.List[t.Union[str, int]] = [cmd] ... if self.socket_name: ... cmd_args.insert(0, f"-L{self.socket_name}") ... cmd_args.insert(0, "-f/dev/null") ... return tmux_cmd(*cmd_args, *args) ... ... default_option_scope = OptionScope.Server
>>> MyServer()._show_options_raw() <libtmux.common.tmux_cmd object at ...>
>>> MyServer()._show_options_raw().stdout [...]
Resolve tmux_bin from self (Server) or self.server (Session/Window/Pane).
Clients attached to this tmux server.
Each attached terminal is a separate
Client.server.clientsreturns the typed view;client.client_readonly,client.client_termtype,client.client_sessionetc. read tmux’sclient_*format tokens.Returns an empty
QueryListwhen tmux’slist-clientsfails for any reason — no running daemon, a missing socket, a permission error, or a subprocess failure. To distinguish “no clients attached” from “tmux unreachable”, callServer.is_alive()orServer.raise_if_dead().Examples
>>> with control_mode() as ctl: ... names = [c.client_name for c in server.clients] ... ctl.client_name in names True
Show environment variable
$ tmux show-environment -t [session] <name>.Return the value of a specific variable if the name is specified.
Added in version 0.13.
Remove environment variable
$ tmux set-environment -r <name>.- Parameters:
name (
str) – The environment variable name, e.g. ‘PATH’.- Raises:
ValueError– If tmux returns an error.- Return type:
Run a hook immediately. Useful for testing.
- Parameters:
hook (
str)scope (
OptionScope|_DefaultOptionScope|None)
- Return type:
Self
Set environment
$ tmux set-environment <name> <value>.- Parameters:
- Raises:
ValueError– If tmux returns an error.- Return type:
Set hook for tmux target.
Wraps
$ tmux set-hook <hook> <value>.- Parameters:
- Raises:
- Return type:
Self
Set multiple indexed hooks at once.
- Parameters:
hook (
str) – Hook name, e.g. ‘session-renamed’values (
HookValues) – Values to set. Can be: - dict[int, str]: {0: ‘cmd1’, 1: ‘cmd2’} - explicit indices - SparseArray[str]: preserves indices from another hook - list[str]: [‘cmd1’, ‘cmd2’] - sequential indices starting at 0clear_existing (
bool) – If True, unset all existing hook values firstscope (
OptionScope|None) – Scope for the hook
- Returns:
Returns self for method chaining.
- Return type:
Self
Examples
Set hooks with explicit indices:
>>> session.set_hooks('session-renamed', { ... 0: 'display-message "hook 0"', ... 1: 'display-message "hook 1"', ... }) Session($...)
>>> hooks = session.show_hook('session-renamed') >>> sorted(hooks.keys()) [0, 1]
>>> session.unset_hook('session-renamed') Session($...)
Set hooks from a list (sequential indices):
>>> session.set_hooks('after-new-window', [ ... 'select-pane -t 0', ... 'send-keys "clear" Enter', ... ]) Session($...)
>>> hooks = session.show_hook('after-new-window') >>> sorted(hooks.keys()) [0, 1]
Replace all existing hooks with
clear_existing=True:>>> session.set_hooks( ... 'session-renamed', ... {0: 'display-message "new"'}, ... clear_existing=True, ... ) Session($...)
>>> hooks = session.show_hook('session-renamed') >>> sorted(hooks.keys()) [0]
>>> session.unset_hook('session-renamed') Session($...)
>>> session.unset_hook('after-new-window') Session($...)
Set option for tmux target.
Wraps
$ tmux set-option <option> <value>.- Parameters:
option (
str) – option to set, e.g. ‘aggressive-resize’value (
str) – option value. True/False will turn in ‘on’ and ‘off’, also accepts string of ‘on’ or ‘off’ directly.deprecated: (
..) – 0.28: Deprecated bygfor global, useglobal_instead.scope (
OptionScope|_DefaultOptionScope|None)
- Raises:
- Return type:
Self
Examples
>>> import typing as t >>> from libtmux.common import tmux_cmd >>> from libtmux.constants import OptionScope >>> from libtmux._internal.sparse_array import SparseArray
>>> class MyServer(OptionsMixin): ... socket_name = server.socket_name ... def cmd(self, cmd: str, *args: object): ... cmd_args: t.List[t.Union[str, int]] = [cmd] ... if self.socket_name: ... cmd_args.insert(0, f"-L{self.socket_name}") ... cmd_args.insert(0, "-f/dev/null") ... return tmux_cmd(*cmd_args, *args) ... ... default_option_scope = OptionScope.Server
>>> MyServer().set_option('escape-time', 1250) <libtmux.options.MyServer object at ...>
>>> MyServer()._show_option('escape-time') 1250
>>> MyServer().set_option('escape-time', 495) <libtmux.options.MyServer object at ...>
>>> MyServer()._show_option('escape-time') 495
Show environment
$ tmux show-environment -t [session].Return dict of environment variables for the session.
Changed in version 0.13: Removed per-item lookups. Use
libtmux.common.EnvironmentMixin.getenv().- Returns:
environmental variables in dict, if no name, or str if name entered.
- Return type:
Return value for a hook.
For array hooks (e.g.,
session-renamed), returns aSparseArraywith hook values at their original indices. Use.keys()for indices and.values()for values.- Parameters:
hook (
str) – Hook name to queryglobal_ (
bool)scope (
OptionScope|_DefaultOptionScope|None)
- Returns:
Hook value. For array hooks, returns SparseArray.
- Return type:
str|int|SparseArray[str] |None- Raises:
Examples
>>> session.set_hook('session-renamed[0]', 'display-message "test"') Session($...)
>>> hooks = session.show_hook('session-renamed') >>> isinstance(hooks, SparseArray) True
>>> sorted(hooks.keys()) [0]
>>> session.unset_hook('session-renamed') Session($...)
Return a dict of hooks for the target.
- Parameters:
global (
bool,optional) – Pass-gflag for global hooks, default False.scope (
OptionScope|_DefaultOptionScope|None,optional) – Hook scope (Server/Session/Window/Pane), defaults to object’s scope.
- Returns:
Dictionary mapping hook names to their values.
- Return type:
HookDict
Examples
>>> session.set_hook('session-renamed[0]', 'display-message "test"') Session($...)
>>> hooks = session.show_hooks() >>> isinstance(hooks, dict) True
>>> 'session-renamed[0]' in hooks True
>>> session.unset_hook('session-renamed') Session($...)
Return option value for the target.
- Parameters:
- Raises:
- Return type:
Examples
>>> import typing as t >>> from libtmux.common import tmux_cmd >>> from libtmux.constants import OptionScope
>>> class MyServer(OptionsMixin): ... socket_name = server.socket_name ... def cmd(self, cmd: str, *args: object): ... cmd_args: t.List[t.Union[str, int]] = [cmd] ... if self.socket_name: ... cmd_args.insert(0, f"-L{self.socket_name}") ... cmd_args.insert(0, "-f/dev/null") ... return tmux_cmd(*cmd_args, *args) ... ... default_option_scope = OptionScope.Server
>>> MyServer().cmd('new-session', '-d') <libtmux.common.tmux_cmd object at ...>
>>> MyServer().show_option('exit-unattached', global_=True) False
Return all options for the target.
- Parameters:
global (
bool,optional) – Pass-gflag for global options, default False.scope (
OptionScope|_DefaultOptionScope|None,optional) – Option scope (Server/Session/Window/Pane), defaults to object’s scope.include_hooks (
bool,optional) – Include hook options (-Hflag).include_inherited (
bool,optional) – Include inherited options (-Aflag).quiet (
bool,optional) –Suppress errors silently (
-qflag).Added in version 0.56.
global_ (
bool)
- Returns:
Dictionary with all options, arrays exploded and values converted.
- Return type:
ExplodedComplexUntypedOptionsDict- Raises:
Examples
>>> options = server.show_options() >>> isinstance(options, dict) True
>>> 'buffer-limit' in options True
Unset environment variable
$ tmux set-environment -u <name>.- Parameters:
name (
str) – The environment variable name, e.g. ‘PATH’.- Raises:
ValueError– If tmux returns an error.- Return type:
Unset hook for tmux target.
Wraps
$ tmux set-hook -u <hook>/$ tmux set-hook -U <hook>- Parameters:
hook (
str) – hook to unset, e.g. ‘after-show-environment’scope (
OptionScope|_DefaultOptionScope|None)
- Raises:
- Return type:
Self
Unset option for tmux target.
Wraps
$ tmux set-option -u <option>/$ tmux set-option -U <option>- Parameters:
option (
str) – option to unset, e.g. ‘aggressive-resize’scope (
OptionScope|_DefaultOptionScope|None)
- Raises:
- Return type:
Self
Examples
>>> import typing as t >>> from libtmux.common import tmux_cmd >>> from libtmux.constants import OptionScope
>>> class MyServer(OptionsMixin): ... socket_name = server.socket_name ... def cmd(self, cmd: str, *args: object): ... cmd_args: t.List[t.Union[str, int]] = [cmd] ... if self.socket_name: ... cmd_args.insert(0, f"-L{self.socket_name}") ... cmd_args.insert(0, "-f/dev/null") ... return tmux_cmd(*cmd_args, *args) ... ... default_option_scope = OptionScope.Server
>>> MyServer().set_option('escape-time', 1250) <libtmux.options.MyServer object at ...>
>>> MyServer()._show_option('escape-time') 1250
>>> MyServer().unset_option('escape-time') <libtmux.options.MyServer object at ...>
>>> isinstance(MyServer()._show_option('escape-time'), int) True
Sessions, optionally filtered by tmux before rows are returned.
Like
Server.sessionsbut adds an optionalfilterkwarg passed to$ tmux list-sessions -f <filter>.- Parameters:
filter (
str,optional) –tmux format expression (
-fflag). tmux omits sessions whose expanded expression is false before libtmux builds objects.Warning
tmux silently expands a malformed filter (unclosed
#{...}, unknown format token) to empty, which the filter treats as false — every row is suppressed and no stderr is emitted. A bad filter is indistinguishable from “filter matched nothing”; verify filter syntax against the FORMATS section oftmux(1).Added in version 0.57.
- Return type:
See also
Server.sessionsunfiltered
QueryListof every session (Python-side.filter()runs against this).- tmux-native Filtering with search_*()
when to pick
search_*overQueryList.filter().
Examples
>>> server.new_session(session_name='gap7_alpha') Session($... gap7_alpha) >>> server.new_session(session_name='other_beta') Session($... other_beta) >>> matches = server.search_sessions(filter='#{m:gap7_*,#{session_name}}') >>> [s.session_name for s in matches] ['gap7_alpha']
All windows across sessions, optionally filtered by tmux.
Like
Server.windowsbut with afilterkwarg passed to$ tmux list-windows -a -f <filter>.- Parameters:
filter (
str,optional) –tmux format expression (
-fflag).Warning
tmux silently expands a malformed filter (unclosed
#{...}, unknown format token) to empty, which the filter treats as false — every row is suppressed and no stderr is emitted. A bad filter is indistinguishable from “filter matched nothing”; verify filter syntax against the FORMATS section oftmux(1).Added in version 0.57.
- Return type:
See also
Server.windowsunfiltered
QueryListof every window across every session (Python-side.filter()runs against this).- tmux-native Filtering with search_*()
when to pick
search_*overQueryList.filter().
Examples
>>> sess = server.new_session(session_name='gap7_win_demo') >>> _ = sess.new_window(window_name='gap7_target') >>> _ = sess.new_window(window_name='other_window') >>> matches = server.search_windows(filter='#{m:gap7_*,#{window_name}}') >>> any(w.window_name == 'gap7_target' for w in matches) True >>> any(w.window_name == 'other_window' for w in matches) False
All panes across the server, optionally filtered by tmux.
Like
Server.panesbut with afilterkwarg passed to$ tmux list-panes -a -f <filter>. tmux drops non-matching panes before libtmux builds objects.- Parameters:
filter (
str,optional) –tmux format expression (
-fflag). Example:'#{m:%5,#{pane_id}}'(id match) or'#{C/i:libtmux,#{pane_current_command}}'(case-insensitive substring on the current command).Warning
tmux silently expands a malformed filter (unclosed
#{...}, unknown format token) to empty, which the filter treats as false — every row is suppressed and no stderr is emitted. A bad filter is indistinguishable from “filter matched nothing”; verify filter syntax against the FORMATS section oftmux(1).Added in version 0.57.
- Return type:
See also
Server.panesunfiltered
QueryListof every pane (Python-side.filter()runs against this).- tmux-native Filtering with search_*()
when to pick
search_*overQueryList.filter().
Examples
>>> sess = server.new_session(session_name='gap7_pane_demo') >>> window = sess.active_window >>> target_pane = window.split() >>> matches = server.search_panes( ... filter=f'#{{m:{target_pane.pane_id},#{{pane_id}}}}' ... ) >>> [p.pane_id for p in matches] == [target_pane.pane_id] True
- Return type:
Return list of panes in
dictform.Retrieved from
$ tmux(1) list-panesstdout.The
listis derived fromstdoutinutil.tmux_cmdwhich wrapssubprocess.Popen.Deprecated since version 0.17: Deprecated in favor of
panes.- Return type:
list[PaneDict]
Return session by id. Deprecated in favor of
sessions.get().Deprecated since version 0.16: Deprecated by
sessions.get().
Filter through sessions, return list of
Session.Deprecated since version 0.17: Deprecated by
session.filter().
Filter through sessions, return first
Session.Deprecated since version 0.17: Slated to be removed in favor of
sessions.get().
Return list of windows in
dictform.Retrieved from
$ tmux(1) list-windowsstdout.The
listis derived fromstdoutincommon.tmux_cmdwhich wrapssubprocess.Popen.Deprecated since version 0.17: Slated to be removed in favor of
windows.- Return type:
list[WindowDict]
Property / alias to return
_list_sessions().Deprecated since version 0.17: Slated to be removed in favor of
sessions.