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.
-
child_id_attribute = 'session_id'¶attribute
Unique child ID used by
TmuxRelationalObject
-
formatter_prefix = 'server_'¶attribute
Namespace used for
TmuxMappingObject
-
attribute
For option management.
-
attribute
For hook management.
When not a user (custom) option, scope can be implied.
Custom path to tmux binary. Falls back to
shutil.which("tmux").
-
socket_name = None¶attribute
Passthrough to
[-L socket-name]
-
socket_path = None¶attribute
Passthrough to
[-S socket-path]
-
config_file = None¶attribute
Passthrough to
[-f file]
-
colors = None¶attribute
256or88
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. :raisessubprocess.CalledProcessError: When the tmux server is not running (non-zero exit fromlist-sessions). :raises >>> tmux = Server(socket_name=”no_exist”): :raises >>> try:: :raises … tmux.raise_if_dead(): :raises … except Exception as e:: :raises … print(type(e)): :raises <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.
:raises
exc.BadSessionName:
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.
:raises
exc.BadSessionName:
Switch tmux client.
:raises
exc.BadSessionName:
Attach tmux session.
:raises
exc.BadSessionName:
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 session
y (int | str, optional) – Force the specified height instead of the tmux default for a detached session
args (Any)
kwargs (Any)
- Return type:
:raises
exc.BadSessionName: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()
-
_add_option = None¶attribute
Return value for the hook.
- Parameters:
hook (str)
global_ (bool)
scope (OptionScope | _DefaultOptionScope | None)
- Return type:
:raises
exc.OptionError,exc.UnknownOption,: :raisesexc.InvalidOption,exc.AmbiguousOption:
Return option value for the target.
todo: test and return True/False for on/off string
:raises
exc.OptionError,exc.UnknownOption,: :raisesexc.InvalidOption,exc.AmbiguousOption: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.
:raises
exc.OptionError,exc.UnknownOption,: :raisesexc.InvalidOption,exc.AmbiguousOption: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.
- Parameters:
g (bool, optional) –
Deprecated since version 0.50.0: Use
global_instead.scope (OptionScope | _DefaultOptionScope | None)
- Return type:
ExplodedComplexUntypedOptionsDict
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.
- Parameters:
g (bool, optional) –
Deprecated since version 0.50.0: Use
global_instead.scope (OptionScope | _DefaultOptionScope | None)
- Return type:
UntypedOptionsDict
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.
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).
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>.:raises
exc.OptionError,exc.UnknownOption,: :raisesexc.InvalidOption,exc.AmbiguousOption:
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 0
clear_existing (bool) – If True, unset all existing hook values first
scope (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 by
gfor global, useglobal_instead.scope (OptionScope | _DefaultOptionScope | None)
- Return type:
Self
:raises
exc.OptionError,exc.UnknownOption,: :raisesexc.InvalidOption,exc.AmbiguousOption: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 query
global_ (bool)
scope (OptionScope | _DefaultOptionScope | None)
- Returns:
Hook value. For array hooks, returns SparseArray.
- Return type:
str | int | SparseArray[str] | None
:raises
exc.OptionError,exc.UnknownOption,: :raisesexc.InvalidOption,exc.AmbiguousOption: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.
:raises
exc.OptionError,exc.UnknownOption,: :raisesexc.InvalidOption,exc.AmbiguousOption: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).global_ (bool)
- Returns:
Dictionary with all options, arrays exploded and values converted.
- Return type:
ExplodedComplexUntypedOptionsDict
:raises
exc.OptionError,exc.UnknownOption,: :raisesexc.InvalidOption,exc.AmbiguousOption: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)
- Return type:
Self
:raises
exc.OptionError,exc.UnknownOption,: :raisesexc.InvalidOption,exc.AmbiguousOption:
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)
- Return type:
Self
:raises
exc.OptionError,exc.UnknownOption,: :raisesexc.InvalidOption,exc.AmbiguousOption: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
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 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.