Note

tmuxp is usable but still needs your help reporting errors, bugs and usability feedback. If you encounter an error, please post on the Issue tracker.

API Reference

See also

Python API Quickstart to see how you can control tmux via python API calls.

Server Object

class tmuxp.Server(socket_name=None, socket_path=None, config_file=None, colors=None, **kwargs)

Bases: tmuxp.util.TmuxRelationalObject

The tmux(1) server.

When instantiated, provides the t global. stores information on live, running tmux server.

childIdAttribute = u'session_id'

unique child ID key

socket_name = None

[-L socket-name]

socket_path = None

[-S socket-path]

config_file = None

[-f file]

colors = None

-2 or -8

tmux(*args, **kwargs)

Return util.tmux send tmux commands with sockets, colors.

Return type:util.tmux
_list_sessions()

Return list of sessions in dict form.

Retrieved from $ tmux(1) list-sessions stdout.

The list is derived from stdout in util.tmux which wraps Subprocess.Popen().

Return type:list of dict
_sessions

Property / alias to return _list_sessions().

list_sessions()

Return list of Session from the tmux(1) session.

Return type:list of Session
sessions

Property / alias to return list_sessions().

children

Alias of sessions.

_list_windows()

Return list of windows in dict form.

Retrieved from $ tmux(1) list-windows stdout.

The list is derived from stdout in util.tmux which wraps Subprocess.Popen().

Return type:list
_update_windows()

Update internal window data and return self for chainability.

Return type:Server
_list_panes()

Return list of panes in dict form.

Retrieved from $ tmux(1) list-panes stdout.

The list is derived from stdout in util.tmux which wraps Subprocess.Popen().

Return type:list
_update_panes()

Update internal pane data and return self for chainability.

Return type:Server
attached_sessions()

Return active Session object.

This will not work where multiple tmux sessions are attached.

Return type:Server
has_session(target_session)

Return True if session exists. $ tmux has-session.

Param:target_session: str of session name.
Return type:bool
kill_server()

$ tmux kill-server.

findWhere(attrs)

Return object on first match.

Based on .findWhere() from underscore.js.

getById(id)

Return object based on childIdAttribute.

Based on .get() from backbone.js.

Parameters:id (string) –
Return type:object
kill_session(target_session=None)

Kill the tmux session with $ tmux kill-session, return self.

Param:target_session: str. note this accepts fnmatch(3). ‘asdf’ will kill ‘asdfasd’.
Return type:Server
where(attrs, first=False)

Return objects matching child objects properties.

Based on .where() from underscore.js.

Parameters:attrs (dict) – tmux properties to match
Return type:list
switch_client(target_session)

$ tmux switch-client.

Param:target_session: str. name of the session. fnmatch(3) works.
attach_session(target_session=None)

$ tmux attach-session aka alias: $ tmux attach.

Param:target_session: str. name of the session. fnmatch(3) works.
new_session(session_name=None, kill_session=False, attach=False, *args, **kwargs)

Return Session from $ tmux new-session.

Uses -P flag to print session info, -F for return formatting returns new Session object.

$ tmux new-session -d will create the session in the background $ tmux new-session -Ad will move to the session name if it already exists. todo: make an option to handle this.

Parameters:
  • session_name (string) –

    session name:

    $ tmux new-session -s <session_name>
  • detach (bool) –

    create session background:

    $ tmux new-session -d
  • attach_if_exists (bool) – if the session_name exists, attach it. if False, this method will raise a tmuxp.exc.TmuxSessionExists exception
  • kill_session (bool) – Kill current session if $ tmux has-session Useful for testing workspaces.
Return type:

Session

Session Object

class tmuxp.Session(server=None, **kwargs)

Bases: tmuxp.util.TmuxMappingObject, tmuxp.util.TmuxRelationalObject

tmux(1) session.

Holds Window objects.

tmux(*args, **kwargs)

Return Server.tmux().

Return type:Server.tmux
attach_session(target_session=None)

Return $ tmux attach-session aka alias: $ tmux attach.

Param:target_session: str. name of the session. fnmatch(3) works.
kill_session()

$ tmux kill-session.

switch_client(target_session=None)

$ tmux kill-session.

Param:target_session: str. note this accepts fnmatch(3). ‘asdf’ will kill asdfasd
rename_session(new_name)

Rename session and return new Session object.

Parameters:rename_session (string) – new session name
Return type:Session
new_window(window_name=None, start_directory=None, attach=True, window_index=u'')

Return Window from $ tmux new-window.

Note

By default, this will make the window active. For the new window to be created and not set to current, pass in attach=False.

Parameters:window_name – window name.
$ tmux new-window -n <window_name> -c <start_directory>
Parameters:
  • start_directory (string) – specifies the working directory in which the new created.
  • attach – make new window the current window after creating it, default True.
  • type – bool
Return type:

Window

kill_window(target_window=None)

$ tmux kill-window.

Kill the current window or the window at target-window. removing it from any sessions to which it is linked.

Parameters:target_window (string) – the target window.
_windows

Property / alias to return _list_windows().

list_windows()

Return a list of Window from the tmux(1) session.

Return type:Window
windows

Property / alias to return list_windows().

children

Alias of windows.

attached_window()

Return active Window object.

Return type:Window
select_window(target_window)

Return Window selected via $ tmux select-window.

Param:window: target_window also ‘last-window’ (-l), ‘next-window’ (-n), or ‘previous-window’ (-p)
Return type:Window
Todo:assure -l, -n, -p work.
attached_pane()

Return active Pane object.

set_option(option, value)

Set option $ tmux set-option <option> <value>.

todo: needs tests

Parameters:
  • option (string) – the window option. such as ‘default-shell’.
  • value (string or bool) – window value. True/False will turn in ‘on’ and ‘off’.
show_options(option=None, g=False)

Return a dict of options for the window.

For familiarity with tmux, the option option param forwards to pick a single option, forwarding to Session.show_option().

Parameters:
  • option (string) – optional. show a single option.
  • g (bool) – Pass -g flag for global variable
Return type:

dict

show_option(option, g=False)

Return a list of options for the window.

Todo:test and return True/False for on/off string
Parameters:option (string) – option to return.
Return type:string, int or bool
findWhere(attrs)

Return object on first match.

Based on .findWhere() from underscore.js.

getById(id)

Return object based on childIdAttribute.

Based on .get() from backbone.js.

Parameters:id (string) –
Return type:object
keys()

Return list of keys.

where(attrs, first=False)

Return objects matching child objects properties.

Based on .where() from underscore.js.

Parameters:attrs (dict) – tmux properties to match
Return type:list

Window Object

class tmuxp.Window(session=None, **kwargs)

Bases: tmuxp.util.TmuxMappingObject, tmuxp.util.TmuxRelationalObject

tmux(1) window.

tmux(cmd, *args, **kwargs)

Return Server.tmux() defaulting target_window as target.

Send command to tmux with window_id as target-window.

Specifying ('-t', 'custom-target') or ('-tcustom_target') in args will override using the object’s window_id as target.

Return type:Server.tmux
select_layout(layout=None)

Wrapper for $ tmux select-layout <layout>.

even-horizontal: Panes are spread out evenly from left to right across the window.

even-vertical: Panes are spread evenly from top to bottom.

main-horizontal: A large (main) pane is shown at the top of the window and the remaining panes are spread from left to right in the leftover space at the bottom.

main-vertical: Similar to main-horizontal but the large pane is placed on the left and the others spread from top to bottom along the right.

tiled: Panes are spread out as evenly as possible over the window in both rows and columns.

custom: custom dimensions (see tmux(1) manpages).

Parameters:layout (string) – string of the layout, ‘even-horizontal’, ‘tiled’, etc.
set_window_option(option, value)

Wrapper for $ tmux set-window-option <option> <value>.

Parameters:value (string or bool) – window value. True/False will turn in ‘on’ and ‘off’.
show_window_options(option=None, g=False)

Return a dict of options for the window.

For familiarity with tmux, the option option param forwards to pick a single option, forwarding to Window.show_window_option().

Parameters:
  • option (string) – optional. show a single option.
  • g (bool) – Pass -g flag for global variable
Return type:

dict

show_window_option(option, g=False)

Return a list of options for the window.

todo: test and return True/False for on/off string

Parameters:
  • option (string) – option to return.
  • g (bool) – Pass -g flag, global.
Return type:

string, int

rename_window(new_name)

Return Window object $ tmux rename-window <new_name>.

Parameters:new_name (string) – name of the window
kill_window()

Kill the current Window object. $ tmux kill-window.

move_window(destination)

Move the current Window object $ tmux move-window.

Parameters:destination – the target window or index to move the window to.
select_window()

Select window. Return self.

To select a window object asynchrously. If a window object exists and is no longer longer the current window, w.select_window() will make w the current window.

Return type:Window
select_pane(target_pane)

Return selected Pane through $ tmux select-pane.

Parameters:target_pane (string) – target_pane, or -U,``-D``, -L, -R or -l.
Return type:Pane
last_pane()

Return last pane.

split_window(target=None, start_directory=None, attach=True)

Split window and return the created Pane.

Note

tmux(1) will move window to the new pane if the split-window target is off screen. tmux handles the -d the same way as new-window and attach in Session.new_window.

By default, this will make the window the pane is created in active. To remain on the same window and split the pane in another target window, pass in attach=False.

Used for splitting window and holding in a python object.

Parameters:
  • attach (bool) – make new window the current window after creating it, default True.
  • start_directory (string) – specifies the working directory in which the new created.
  • target (bool) – target_pane to split.
Return type:

Pane

attached_pane()

Return the attached Pane.

Return type:Pane
_panes

Property / alias to return _list_panes().

list_panes()

Return list of Pane for the window.

Return type:list of Pane
panes

Property / alias to return list_panes().

children

Alias of panes.

findWhere(attrs)

Return object on first match.

Based on .findWhere() from underscore.js.

getById(id)

Return object based on childIdAttribute.

Based on .get() from backbone.js.

Parameters:id (string) –
Return type:object
keys()

Return list of keys.

where(attrs, first=False)

Return objects matching child objects properties.

Based on .where() from underscore.js.

Parameters:attrs (dict) – tmux properties to match
Return type:list

Pane Object

class tmuxp.Pane(window=None, **kwargs)

Bases: tmuxp.util.TmuxMappingObject, tmuxp.util.TmuxRelationalObject

tmux(1) pane.

Parameters:windowWindow
tmux(cmd, *args, **kwargs)

Return Server.tmux() defaulting to target_pane as target.

Send command to tmux with pane_id as target-pane.

Specifying ('-t', 'custom-target') or ('-tcustom_target') in args will override using the object’s pane_id as target.

Return type:Server.tmux
send_keys(cmd, enter=True)

$ tmux send-keys to the pane.

Parameters:
  • cmd (str) – Text or input into pane
  • enter (bool) – Send enter after sending the input.
clear()

Clear pane.

reset()

Reset and clear pane history.

split_window(attach=False)

Split window at pane and return newly created Pane.

Parameters:attach (bool) – Attach / select pane after creation.
Return type:Pane.
set_width(width)

Set width of pane.

Parameters:width (int) – pane width, in cells.
set_height(height)

Set height of pane.

Parameters:height (int) – pane height, in cells.
resize_pane(*args, **kwargs)

$ tmux resize-pane of pane and return self.

Parameters:target_pane (string) – target_pane, or -U,``-D``, -L, -R.
Return type:Pane
enter()

Send carriage return to pane.

$ tmux send-keys send Enter to the pane.

select_pane()

Select pane. Return self.

To select a window object asynchrously. If a pane object exists and is no longer longer the current window, w.select_pane() will make p the current pane.

Return type:pane
findWhere(attrs)

Return object on first match.

Based on .findWhere() from underscore.js.

getById(id)

Return object based on childIdAttribute.

Based on .get() from backbone.js.

Parameters:id (string) –
Return type:object
keys()

Return list of keys.

where(attrs, first=False)

Return objects matching child objects properties.

Based on .where() from underscore.js.

Parameters:attrs (dict) – tmux properties to match
Return type:list

Internals

class tmuxp.util.TmuxRelationalObject

Base Class for managing tmux object child entities.

Manages collection of child objects (a Server has a collection of Session objects, a Session has collection of Window)

Children of TmuxRelationalObject are going to have a self.children, self.childIdAttribute and self.list_children.

Object .children .childIdAttribute method
Server self._sessions ‘session_id’ Server.list_sessions()
Session self._windows ‘window_id’ Session.list_windows()
Window self._panes ‘pane_id’ Window.list_panes()
Pane      
findWhere(attrs)

Return object on first match.

Based on .findWhere() from underscore.js.

getById(id)

Return object based on childIdAttribute.

Based on .get() from backbone.js.

Parameters:id (string) –
Return type:object
where(attrs, first=False)

Return objects matching child objects properties.

Based on .where() from underscore.js.

Parameters:attrs (dict) – tmux properties to match
Return type:list
class tmuxp.util.TmuxMappingObject

Base: collections.MutableMapping.

Convenience container. Base class for Pane, Window, Session and Server.

Instance attributes for useful information tmux(1) uses for Session, Window, Pane, stored self._TMUX. For example, a Window will have a window_id and window_name.

keys()

Return list of keys.

class tmuxp.util.tmux(*args, **kwargs)

subprocess for tmux(1).

Usage:

proc = tmux('new-session', '-s%' % 'my session')

if proc.stderr:
    raise exc.TmuxpException(
        'Command: %s returned error: %s' % (proc.cmd, proc.stderr)
    )

print('tmux command returned %s' % proc.stdout)

Equivalent to:

$ tmux new-session -s my session
static util.has_required_tmux_version(version=None)

Return if tmux meets version requirement. Version >1.8 or above.

Versionchanged:0.1.7 Versions will now remove trailing letters per Issue 55.
static util.oh_my_zsh_auto_title()

Give warning and offer to fix DISABLE_AUTO_TITLE.

see: https://github.com/robbyrussell/oh-my-zsh/pull/257

static util.which(exe=None)

Return path of bin. Python clone of /usr/bin/which.

from salt.util - https://www.github.com/saltstack/salt - license apache

Parameters:exe (string) – Application to search PATHs for.
Return type:string

Command Line

static cli.startup(config_dir)

Initialize CLI.

Parameters:config_dir (string) – Config directory to search
static cli.prompt(name, default=None)

Return user input from command line.

prompt(), prompt_bool() and prompt_choices() are from flask-script. See the flask-script license.

Parameters:
  • name – prompt text
  • default – default value if no input provided.
Return type:

string

static cli.prompt_bool(name, default=False, yes_choices=None, no_choices=None)

Return user input from command line and converts to boolean value.

Parameters:
  • name – prompt text
  • default – default value if no input provided.
  • yes_choices – default ‘y’, ‘yes’, ‘1’, ‘on’, ‘true’, ‘t’
  • no_choices – default ‘n’, ‘no’, ‘0’, ‘off’, ‘false’, ‘f’
Return type:

bool

static cli.prompt_choices(name, choices, default=None, no_choice=(u'none', ))

Return user input from command line from set of provided choices.

Parameters:
  • name – prompt text
  • choices – list or tuple of available choices. Choices may be single strings or (key, value) tuples.
  • default – default value if no input provided.
  • no_choice – acceptable list of strings for “null choice”
Return type:

str

static cli.setup_logger(logger=None, level=u'INFO')

Setup logging for CLI use.

Parameters:logger (Logger) – instance of logger
static cli.get_parser()

Return argparse.ArgumentParser instance for CLI.

static cli.load_workspace(config_file, args)

Build config workspace.

Parameters:
  • config_file – full path to config file
  • type – string

Configuration

Finding

static config.is_config_file(filename, extensions=[u'.yml', u'.yaml', u'.json'])

Return True if file has a valid config file type.

Parameters:
  • filename (string) – filename to check (e.g. mysession.json).
  • extensions (list or string) – filetypes to check (e.g. ['.yaml', '.json']).
Return type:

bool

static config.in_dir(config_dir=u'/home/docs/.tmuxp', extensions=[u'.yml', u'.yaml', u'.json'])

Return a list of configs in config_dir.

Parameters:
  • config_dir (string) – directory to search
  • extensions (list) – filetypes to check (e.g. ['.yaml', '.json']).
Return type:

list

static config.in_cwd()

Return list of configs in current working directory.

If filename is .tmuxp.py, .tmuxp.json, .tmuxp.yaml.

Return type:list

Import and export

static config.validate_schema(sconf)

Return True if config schema is correct.

Parameters:sconf (dict) – session configuration
Return type:bool
static config.expand(sconf, cwd=None)

Return config with shorthand and inline properties expanded.

This is necessary to keep the code in the WorkspaceBuilder clean and also allow for neat, short-hand configurations.

As a simple example, internally, tmuxp expects that config options like shell_command are a list (array):

'shell_command': ['htop']

tmuxp configs allow for it to be simply a string:

'shell_command': 'htop'

Kaptan will load JSON/YAML files into python dicts for you.

Parameters:
  • sconf (dict) – the configuration for the session
  • cwd – directory to expand relative paths against. should be the dir of the config directory.
Return type:

dict

static config.inline(sconf)

Return config in inline form, opposite of config.expand().

Parameters:sconf (dict) – unexpanded config file
Return type:dict
static config.trickle(sconf)

Return a dict with “trickled down” / inherited config values.

This will only work if config has been expanded to full form with config.expand().

tmuxp allows certain commands to be default at the session, window level. shell_command_before trickles down and prepends the shell_command for the pane.

Parameters:sconf (dict) – the session configuration
Return type:dict
static config.import_teamocil(sconf)

Return tmuxp config from a teamocil yaml config.

Todo:change ‘root’ to a cd or start_directory
Todo:width in pane -> main-pain-width
Todo:with_env_var
Todo:clear
Todo:cmd_separator
Parameters:sconf (dict) – python dict for session configuration
static config.import_tmuxinator(sconf)

Return tmuxp config from a tmuxinator yaml config.

Parameters:sconf (dict) – python dict for session configuration
Return type:dict

Workspace Builder

class tmuxp.WorkspaceBuilder(sconf, server=None)

Load workspace from session dict.

Build tmux workspace from a configuration. Creates and names windows, sets options, splits windows into panes.

The normal phase of loading is:

  1. kaptan imports json/yaml/ini. .get() returns python dict:

    import kaptan
    sconf = kaptan.Kaptan(handler='yaml')
    sconf = sconfig.import_config(self.yaml_config).get()
    

    or from config file with extension:

    import kaptan
    sconf = kaptan.Kaptan()
    sconf = sconfig.import_config('path/to/config.yaml').get()
    

    kaptan automatically detects the handler from filenames.

  2. config.expand() sconf inline shorthand:

    from tmuxp import config
    sconf = config.expand(sconf)
    
  3. config.trickle() passes down default values from session -> window -> pane if applicable:

    sconf = config.trickle(sconf)
    
  4. (You are here) We will create a Session (a real tmux(1) session) and iterate through the list of windows, and their panes, returning full Window and Pane objects each step of the way:

    workspace = WorkspaceBuilder(sconf=sconf)
    

It handles the magic of cases where the user may want to start a session inside tmux (when $TMUX is in the env variables).

build(session=None)

Build tmux workspace in session.

Optionally accepts session to build with only session object.

Without session, it will use Server at self.server passed in on initialization to create a new Session object.

Parameters:session (Session) –
  • session to build workspace in
iter_create_panes(w, wconf)

Return Pane iterating through window config dict.

Run shell_command with $ tmux send-keys.

Parameters:
  • w (Window) – window to create panes for
  • wconf (dict) – config section for window
Return type:

tuple(Pane, pconf)

iter_create_windows(s)

Return Window iterating through session config dict.

Generator yielding Window by iterating through sconf['windows'].

Applies window_options to window.

Parameters:sessionSession from the config
Return type:tuple(Window, wconf)

Exceptions

exception tmuxp.exc.TmuxpException

Base Exception for Tmuxp Errors.

Also for Python 2.6 compat:
http://stackoverflow.com/a/6029838
exception tmuxp.exc.TmuxSessionExists

Session does not exist in the server.

exception tmuxp.exc.EmptyConfigException

Configuration is empty.

exception tmuxp.exc.ConfigError

Error parsing tmuxp configuration dict.

exception tmuxp.exc.BeforeLoadScriptError(returncode, cmd, output=None)

Exception replacing subprocess.CalledProcessError for util.run_before_script().

exception tmuxp.exc.BeforeLoadScriptNotExists(*args, **kwargs)

Test tools

static helpers.get_test_session_name(server, prefix=u'test tmuxp_')
static helpers.get_test_window_name(session, prefix=u'test tmuxp_')
static helpers.temp_session(*args, **kwds)

Return a context manager with a temporary session.

e.g.:

with temp_session(server) as session:
    session.new_window(window_name='my window')

The session will destroy itself upon closing with Session. kill_session().

If no session_name is entered, get_test_session_name() will make an unused session name.

Args:Same arguments as Server.new_session()
Yields:Temporary session
Return type:Session
static helpers.temp_window(*args, **kwds)

Return a context manager with a temporary window.

e.g.:

with temp_window(session) as window:
    my_pane = window.split_window()

The window will destroy itself upon closing with window. kill_window().

If no window_name is entered, get_test_window_name() will make an unused window name.

Args:Same arguments as Session.new_window()
Yields:Temporary window
Return type:Window