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
class libtmux.Server

Bases: EnvironmentMixin, OptionsMixin, HooksMixin

tmux(1) Server [server_manual].

When instantiated stores information on live, running tmux server.

A tmux socket is a UNIX domain socket, so its path is capped by sockaddr_un – 107 bytes on Linux, 103 on macOS. An explicit socket_path is handed to tmux unchanged, so it is measured here and an over-long one raises SocketPathTooLong from the constructor.

Naming a server is free. A socket_name resolves against $TMUX_TMPDIR when tmux runs, so it is measured then rather than now: a named or bare Server can always be constructed and asked is_alive(), and the first command that would have to bind the socket is what raises. When the depth is not yours to choose – a pytest tmp_path, a nested worktree, a CI checkout under a long workspace prefix – put the socket under tempfile.mkdtemp() or point $TMUX_TMPDIR at something short.

Connecting. Constructing a Server runs no tmux command of its own; it records the socket and settings every later call uses. from_env() reads $TMUX without a subprocess, raises NotInsideTmux when it is unset, and does not check that the server is alive. is_alive() answers a bool and never raises, where raise_if_dead() raises TmuxCommandNotFound or subprocess.CalledProcessError.

Finding one thing. Each from_*_id constructor asks tmux for one object and raises TmuxObjectDoesNotExist when it is not there. get on a listing returns exactly one match, and raises ObjectDoesNotExist for none unless a default is passed, and MultipleObjectsReturned for several. has_session() answers a bool, matches the name exactly unless exact=False, and raises BadSessionName for an empty name or one holding a period or colon.

Listing everything. Each access reads tmux again and returns a QueryList, so a list you keep is a snapshot. sessions and clients answer an empty list when the tmux command fails for any reason, so tell “no sessions” from “tmux unreachable” with is_alive(). windows and panes answer empty only while the daemon is not up and raise on other tmux errors. Windows and panes span every session.

Filtering. filter on a listing runs in Python against the full list. The search_* methods hand tmux a -f format expression instead, and tmux drops rows before any object is built. A malformed expression expands to empty and hides every row without an error.

Creating and destroying. new_session() creates a detached session and returns it. A name already in use raises TmuxSessionExists unless kill_session=True. kill_session() passes its target to tmux, which matches it with fnmatch(3), so asdf also kills asdfasd. kill() stops the server and returns quietly when no daemon is running.

Clients. clients returns typed Client objects and list_clients() returns tmux’s raw lines. Switching and attaching take a session name, which raises BadSessionName when it is empty or holds a period or colon.

Options, hooks and environment. These calls come from mixins and act on the server scope by default. The option and hook setters return the object, so calls chain, and an unknown or invalid option or hook name raises OptionError or one of its subclasses. The environment calls act on the server’s global environment, and the setters raise ValueError when tmux reports an error.

Buffers and key bindings. Each wraps the tmux command of the same name and raises LibTmuxException when tmux writes to stderr.

Running a command. Anything tmux can do that has no method here goes through cmd(), which adds the socket, config file and color flags and returns a tmux_cmd holding the return code, stdout and stderr. It does not check them. The shell and sourcing helpers do, and raise LibTmuxException.

Parameters:
  • socket_name (str, optional)

  • socket_path (str, optional)

  • config_file (str, optional)

  • colors (str, optional)

  • on_init (callable, optional)

  • socket_name_factory (callable, optional)

  • tmux_bin (str or pathlib.Path, optional)

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

A socket_path is handed to tmux unchanged, so one that cannot fit in a UNIX socket address is refused where it was written:

>>> from libtmux.server import Server as TmuxServer
>>> try:
...     TmuxServer(socket_path="/tmp/" + "d" * 120 + "/sock")
... except exc.SocketPathTooLong as e:
...     print(e.length)
130

A name resolves against $TMUX_TMPDIR, which tmux re-reads when it runs, so its length is only knowable at dispatch. The directory has to exist: tmux falls back to /tmp when it cannot resolve one, and a socket it never binds is not worth measuring. The server builds, and one at an unbindable address is simply not alive:

>>> deep = request.getfixturevalue("tmp_path") / ("d" * 120)
>>> deep.mkdir()
>>> with monkeypatch.context() as m:
...     m.setenv("TMUX_TMPDIR", str(deep))
...     named = TmuxServer(socket_name="dev")
...     named.is_alive()
False

The command that would have had to bind it says so, with the byte count tmux would not have given:

>>> with monkeypatch.context() as m:
...     m.setenv("TMUX_TMPDIR", str(deep))
...     try:
...         named.cmd("list-sessions")
...     except exc.SocketPathTooLong as e:
...         print(e.socket_name)
dev

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.