Context managers

When you create tmux objects through libtmux, they normally live until you explicitly kill them. A context manager hands that cleanup back to Python: you scope an object to a block, and libtmux kills the underlying tmux object the moment you leave it — whether you exit cleanly or an exception unwinds the stack. Session, Window, and Pane work this way.

Server is the exception, and deliberately so: it does not kill itself on the way out unless you ask it to. A server is shared, and a handle on one says nothing about who started it.

Most readers never reach for this. If you’re building a long-running application, you typically let objects persist and tear them down yourself. The context-manager form earns its keep in test fixtures and short-lived scripts, where you want a tmux object to exist for exactly one block and then vanish.

Open two terminals:

Terminal one: start tmux in a separate terminal:

$ tmux

Terminal two, python or ptpython if you have it:

$ python

Import libtmux:

>>> import libtmux

Server context manager

A Server is a handle on a socket, not a connection. The same handle addresses a daemon whether or not your process started it, and a bare Server() addresses the default socket — usually the tmux you have been working in all day. Scoping one to a block is not grounds to destroy it, so leaving the block changes nothing:

>>> already_running = Server()
>>> session = already_running.new_session(session_name='important-work')
>>> with Server(socket_name=already_running.socket_name) as scoped:
...     print(scoped.is_alive())
True
>>> print([session.session_name for session in already_running.sessions])
['important-work']

Here Server is this repository’s isolated TestServer factory; each call gets a unique socket and registered cleanup. In application code, use libtmux.Server(socket_path=..., kill_on_exit=True) with a socket inside a tempfile.TemporaryDirectory. Nest the server context inside the directory context so the server stops before its socket is removed.

When you intend to destroy the server and all its sessions, set kill_on_exit:

>>> with Server(socket_name='libtmux_doctest_ctx', kill_on_exit=True) as disposable:
...     _ = disposable.new_session()
>>> print(disposable.is_alive())
False

The default also preserves a server started during the block, including one started by another client, and an exception from the block propagates without destroying the server. Constructing a handle does not establish ownership.

Session, window and pane contexts still destroy their selected object on exit, including objects retrieved from an existing server. Use those contexts only when you intend to destroy that object.

Session context manager

You create a temporary session that will be killed when you’re done:

>>> server = Server()
>>> with server.new_session() as session:
...     print(session in server.sessions)
...     window = session.new_window()
True
>>> print(session in server.sessions)  # Session is killed after exiting context
False

Window context manager

You create a temporary window that will be killed when you’re done:

>>> server = Server()
>>> session = server.new_session()
>>> with session.new_window() as window:
...     print(window in session.windows)
...     pane = window.split()
True
>>> print(window in session.windows)  # Window is killed after exiting context
False

__exit__() kills the window even when new_window() returned an existing window for select_existing=True, so do not wrap a reuse call in with.

Pane context manager

You create a temporary pane that will be killed when you’re done:

>>> server = Server()
>>> session = server.new_session()
>>> window = session.new_window()
>>> with window.split() as pane:
...     print(pane in window.panes)
...     pane.send_keys('echo "Hello"')
True
>>> print(pane in window.panes)  # Pane is killed after exiting context
False

Nested context managers

For an isolated setup, pass kill_on_exit=True on the outer server to build a whole tmux hierarchy at once and tear every layer down on exit:

>>> with Server(socket_name='libtmux_doctest_nested', kill_on_exit=True) as disposable:
...     with disposable.new_session() as nested_session:
...         with nested_session.new_window() as nested_window:
...             with nested_window.split() as nested_pane:
...                 nested_pane.send_keys('echo "Hello"')
>>> disposable.is_alive()
False

This tears down each layer in reverse order (pane → window → session → server):

  1. The pane is killed when exiting its context

  2. The window is killed when exiting its context

  3. The session is killed when exiting its context

  4. The server is killed when exiting its context because kill_on_exit=True (without it, the server context sends no kill command)

When kill_on_exit is left False, tmux may still exit after its last session ends according to its exit-empty option.

Benefits

Reaching for a context manager buys you a few things. Sessions, windows and panes clean themselves up the moment you leave the block, so you never manually call kill(), kill(), or kill() and the code stays uncluttered. Because cleanup runs on the way out of the block, it fires even when an exception unwinds the stack — so you don’t leak a stray session or pane on the error path. And when you nest contexts, the objects tear down in hierarchical order, which keeps tmux’s own bookkeeping consistent. A server is the exception: call kill() yourself, or ask for it with kill_on_exit.

When to use

Use context managers when you’re writing test fixtures, running short-lived sessions, or managing several tmux servers that each need to disappear cleanly. They also pay off in any script that might raise partway through, or when you’re spinning up an isolated environment that has to be cleaned up afterward.