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)
- class libtmux.Server[source]¶
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.
- Parameters:
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.
When not a user (custom) option, scope can be implied.
- child_id_attribute = 'session_id'¶
Unique child ID used by
TmuxRelationalObject
- formatter_prefix = 'server_'¶
Namespace used for
TmuxMappingObject
- default_option_scope: OptionScope | None = 'SERVER'¶
For option management.
- default_hook_scope: OptionScope | None = 'SERVER'¶
For hook management.
- __init__(socket_name=None, socket_path=None, config_file=None, colors=None, on_init=None, socket_name_factory=None, **kwargs)[source]¶
When not a user (custom) option, scope can be implied.
- socket_name = None¶
Passthrough to
[-L socket-name]
- socket_path = None¶
Passthrough to
[-S socket-path]
- config_file = None¶
Passthrough to
[-f file]
- colors = None¶
256or88
- is_alive()[source]¶
Return True if tmux server alive.
- Return type:
>>> tmux = Server(socket_name="no_exist") >>> assert not tmux.is_alive()
- raise_if_dead()[source]¶
Raise if server not connected.
- Return type:
>>> tmux = Server(socket_name="no_exist") >>> try: ... tmux.raise_if_dead() ... except Exception as e: ... print(type(e)) <class 'subprocess.CalledProcessError'>
- cmd(cmd, *args, target=None)[source]¶
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.
- property attached_sessions: list[Session]¶
Return active :class:`Session`s.
Examples
>>> server.attached_sessions []
- Return type:
list of
Session
- has_session(target_session, exact=True)[source]¶
Return True if session exists.
- Return type:
- Parameters:
- Raises:
- Return type:
- kill()[source]¶
Kill tmux server.
- Return type:
>>> svr = Server(socket_name="testing") >>> svr Server(socket_name=testing)
>>> svr.new_session() Session(...)
>>> svr.is_alive() True
>>> svr.kill()
>>> svr.is_alive() False
- kill_session(target_session)[source]¶
Kill tmux session.
- Return type:
- Parameters:
target_session (str, optional) – target_session: str. note this accepts
fnmatch(3). ‘asdf’ will kill ‘asdfasd’.- Return type:
- Raises:
- switch_client(target_session)[source]¶
Switch tmux client.
- Return type:
- Parameters:
target_session (str) – name of the session. fnmatch(3) works.
- Raises:
- attach_session(target_session=None)[source]¶
Attach tmux session.
- Return type:
- Parameters:
target_session (str) – name of the session. fnmatch(3) works.
- Raises:
- new_session(session_name=None, kill_session=False, attach=False, start_directory=None, window_name=None, window_command=None, x=None, y=None, environment=None, *args, **kwargs)[source]¶
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.- Return type:
Session
- 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 (t.Any)
kwargs (t.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)
- property sessions: QueryList[Session]¶
Sessions contained in server.
Can be accessed via
.sessions.get()and.sessions.filter()
- property windows: QueryList[Window]¶
Windows contained in server’s sessions.
Can be accessed via
.windows.get()and.windows.filter()
- property panes: QueryList[Pane]¶
Panes contained in tmux server (across all windows in all sessions).
Can be accessed via
.panes.get()and.panes.filter()
- _show_hook(hook, global_=False, scope=<libtmux.constants._DefaultOptionScope object>)[source]¶
Return value for the hook.
- Return type:
- Parameters:
hook (str)
global_ (bool)
scope (OptionScope | _DefaultOptionScope | None)
- Raises:
- _show_option(option, global_=False, g=False, scope=<libtmux.constants._DefaultOptionScope object>, ignore_errors=None, include_hooks=None, include_inherited=None)[source]¶
Return option value for the target.
todo: test and return True/False for on/off string
- Return type:
- Parameters:
- Raises:
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
- _show_option_raw(option, global_=False, g=False, scope=<libtmux.constants._DefaultOptionScope object>, ignore_errors=None, include_hooks=None, include_inherited=None)[source]¶
Return raw option output for target.
- Return type:
tmux_cmd
- Parameters:
- Raises:
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
- _show_options(g=False, global_=False, scope=<libtmux.constants._DefaultOptionScope object>, include_hooks=None, include_inherited=None)[source]¶
Return a dict of options for the target.
- Return type:
dict[str,str|int|list[str|int] |dict[str,list[str|int]] |SparseArray[str|int] |None]- Parameters:
g (str, optional) – Pass
-gflag for global variable, default False.global_ (bool | None)
scope (OptionScope | _DefaultOptionScope | None)
include_hooks (bool | None)
include_inherited (bool | 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()._show_options() {...}
- _show_options_dict(g=False, global_=False, scope=<libtmux.constants._DefaultOptionScope object>, include_hooks=None, include_inherited=None)[source]¶
Return dict of options for the target.
- Return type:
- Parameters:
g (str, optional) – Pass
-gflag for global variable, default False.global_ (bool | None)
scope (OptionScope | _DefaultOptionScope | None)
include_hooks (bool | None)
include_inherited (bool | 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()._show_options_dict() {...}
>>> isinstance(MyServer()._show_options_dict(), dict) True
- _show_options_raw(g=False, global_=False, scope=<libtmux.constants._DefaultOptionScope object>, include_hooks=None, include_inherited=None)[source]¶
Return a dict of options for the target.
- Return type:
tmux_cmd
- Parameters:
g (str, optional) – Pass
-gflag for global variable, default False.global_ (bool | None)
scope (OptionScope | _DefaultOptionScope | None)
include_hooks (bool | None)
include_inherited (bool | 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()._show_options_raw() <libtmux.common.tmux_cmd object at ...>
>>> MyServer()._show_options_raw().stdout [...]
- getenv(name)[source]¶
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.
- run_hook(hook, global_=None, scope=<libtmux.constants._DefaultOptionScope object>)[source]¶
Run a hook immediately. Useful for testing.
- Return type:
Self
- Parameters:
hook (str)
global_ (bool | None)
scope (OptionScope | _DefaultOptionScope | None)
- set_hook(hook, value, unset=None, run=None, append=None, g=None, global_=None, scope=<libtmux.constants._DefaultOptionScope object>)[source]¶
Set hook for tmux target.
Wraps
$ tmux set-hook <hook> <value>.- Return type:
Self
- Parameters:
- Raises:
- set_hooks(hook, values, *, clear_existing=False, global_=None, scope=<libtmux.constants._DefaultOptionScope object>)[source]¶
Set multiple indexed hooks at once.
- Return type:
Self
- 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
global (bool | None) – Use global hooks
scope (OptionScope | None) – Scope for the hook
global_ (bool | None)
- 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(option, value, _format=None, prevent_overwrite=None, ignore_errors=None, suppress_warnings=None, append=None, g=None, global_=None, scope=<libtmux.constants._DefaultOptionScope object>)[source]¶
Set option for tmux target.
Wraps
$ tmux set-option <option> <value>.- Return type:
Self
- 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, use global_` instead._format (bool | None)
prevent_overwrite (bool | None)
ignore_errors (bool | None)
suppress_warnings (bool | None)
append (bool | None)
g (bool | None)
global_ (bool | None)
scope (OptionScope | _DefaultOptionScope | None)
- Raises:
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()[source]¶
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().
- show_hook(hook, global_=False, scope=<libtmux.constants._DefaultOptionScope object>)[source]¶
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.- Return type:
str|int|SparseArray[str] |None- 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:
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($...)
- show_hooks(global_=False, scope=<libtmux.constants._DefaultOptionScope object>)[source]¶
Return a dict of hooks for the target.
- Return type:
- 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.
global_ (bool | None)
- 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($...)
- show_option(option, global_=False, g=False, scope=<libtmux.constants._DefaultOptionScope object>, ignore_errors=None, include_hooks=None, include_inherited=None)[source]¶
Return option value for the target.
- Return type:
- Parameters:
- Raises:
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
- show_options(global_=False, scope=<libtmux.constants._DefaultOptionScope object>, include_hooks=None, include_inherited=None)[source]¶
Return all options for the target.
- Return type:
dict[str,str|int|list[str|int] |dict[str,list[str|int]] |SparseArray[str|int] |None]- 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:
Examples
>>> options = server.show_options() >>> isinstance(options, dict) True
>>> 'buffer-limit' in options True
- unset_hook(hook, global_=None, scope=<libtmux.constants._DefaultOptionScope object>)[source]¶
Unset hook for tmux target.
Wraps
$ tmux set-hook -u <hook>/$ tmux set-hook -U <hook>- Return type:
Self
- Parameters:
hook (str) – hook to unset, e.g. ‘after-show-environment’
global_ (bool | None)
scope (OptionScope | _DefaultOptionScope | None)
- Raises:
- unset_option(option, unset_panes=None, global_=None, ignore_errors=None, scope=<libtmux.constants._DefaultOptionScope object>)[source]¶
Unset option for tmux target.
Wraps
$ tmux set-option -u <option>/$ tmux set-option -U <option>- Return type:
Self
- Parameters:
option (str) – option to unset, e.g. ‘aggressive-resize’
unset_panes (bool | None)
global_ (bool | None)
ignore_errors (bool | None)
scope (OptionScope | _DefaultOptionScope | None)
- Raises:
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
- kill_server()[source]¶
Kill tmux server.
- Return type:
Notes
Deprecated since version 0.30: Deprecated in favor of
kill().
- _list_panes()[source]¶
Return list of panes in
dictform.Retrieved from
$ tmux(1) list-panesstdout.The
listis derived fromstdoutinutil.tmux_cmdwhich wrapssubprocess.Popen.Deprecated since version 0.16: Deprecated in favor of
panes.
- _update_panes()[source]¶
Update internal pane data and return
selffor chainability.Deprecated since version 0.16: Deprecated in favor of
panesand returningself.
- get_by_id(session_id)[source]¶
Return session by id. Deprecated in favor of
sessions.get().Deprecated since version 0.16: Deprecated by
sessions.get().
- where(kwargs)[source]¶
Filter through sessions, return list of
Session.Deprecated since version 0.16: Deprecated by
session.filter().
- find_where(kwargs)[source]¶
Filter through sessions, return first
Session.Deprecated since version 0.16: Slated to be removed in favor of
sessions.get().
- _list_windows()[source]¶
Return list of windows in
dictform.Retrieved from
$ tmux(1) list-windowsstdout.The
listis derived fromstdoutincommon.tmux_cmdwhich wrapssubprocess.Popen.Deprecated since version 0.16: Slated to be removed in favor of
windows.
- _update_windows()[source]¶
Update internal window data and return
selffor chainability.Deprecated since version 0.16: Deprecated in favor of
windowsand returningself.- Return type:
- property _sessions: list[dict[str, Any]]¶
Property / alias to return
_list_sessions().Deprecated since version 0.16: Slated to be removed in favor of
sessions.
- _list_sessions()[source]¶
Return list of session object dictionaries.
Deprecated since version 0.16: Slated to be removed in favor of
sessions.