API Reference

See also

Quickstart.

Server Object

class libtmux.Server(socket_name=None, socket_path=None, config_file=None, colors=None, **kwargs)[source]

Bases: libtmux.common.TmuxRelationalObject, libtmux.common.EnvironmentMixin

The tmux(1) server [2].

When instantiated stores information on live, running tmux server.

Parameters:
  • socket_name (str, optional) –
  • socket_path (str, optional) –
  • config_file (str, optional) –
  • colors (str, optional) –

References

[2]
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 = u'session_id'

unique child ID used by TmuxRelationalObject

formatter_prefix = u'server_'

namespace used TmuxMappingObject

socket_name = None

[-L socket-name]

socket_path = None

[-S socket-path]

config_file = None

[-f file]

colors = None

-2 or -8

cmd(*args, **kwargs)[source]

Execute tmux command and return output.

Returns:
Return type:common.tmux_cmd

Notes

Changed in version 0.8: Renamed from .tmux to .cmd.

_list_sessions()[source]

Return list of sessions in dict form.

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

The list is derived from stdout in common.tmux_cmd which wraps subprocess.Popen.

Returns:
Return type:list of dict
_sessions

Property / alias to return _list_sessions().

list_sessions()[source]

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

Returns:
Return type:list of Session
sessions

Property / alias to return list_sessions().

children

Alias sessions for TmuxRelationalObject

_list_windows()[source]

Return list of windows in dict form.

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

The list is derived from stdout in common.tmux_cmd which wraps subprocess.Popen.

Returns:
Return type:list of dict
_update_windows()[source]

Update internal window data and return self for chainability.

Returns:
Return type:Server
_list_panes()[source]

Return list of panes in dict form.

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

The list is derived from stdout in util.tmux_cmd which wraps subprocess.Popen.

Returns:
Return type:list
_update_panes()[source]

Update internal pane data and return self for chainability.

Returns:
Return type:Server
attached_sessions

Return active Session objects.

This will not work where multiple tmux sessions are attached.

Returns:
Return type:list of Session
has_session(target_session, exact=True)[source]

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

Parameters:
  • target_session (str) – session name
  • exact (bool) – match the session name exactly. tmux uses fnmatch by default. Internally prepends = to the session in $ tmux has-session. tmux 2.1 and up only.
Raises:

exc.BadSessionName

Returns:

Return type:

bool

kill_server()[source]

$ tmux kill-server.

find_where(attrs)[source]

Return object on first match.

Changed in version 0.4: Renamed from .findWhere to .find_where.

get_by_id(id)[source]

Return object based on child_id_attribute.

Parameters:val (str) –
Returns:
Return type:object

Notes

Based on .get() from backbone.js.

kill_session(target_session=None)[source]

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

Parameters:target_session (str, optional) – target_session: str. note this accepts fnmatch(3). ‘asdf’ will kill ‘asdfasd’.
Returns:
Return type:Server
Raises:exc.BadSessionName
remove_environment(name)[source]

Remove environment variable $ tmux set-environment -r <name>.

Parameters:name (str) – the environment variable name. such as ‘PATH’.
set_environment(name, value)[source]

Set environment $ tmux set-environment <name> <value>.

Parameters:
  • name (str) – the environment variable name. such as ‘PATH’.
  • option (str) – environment value.
show_environment(name=None)[source]

Show environment $ tmux show-environment -t [session] <name>.

Return dict of environment variables for the session or the value of a specific variable if the name is specified.

Parameters:name (str) – the environment variable name. such as ‘PATH’.
Returns:environmental variables in dict, if no name, or str if name entered.
Return type:str or dict
unset_environment(name)[source]

Unset environment variable $ tmux set-environment -u <name>.

Parameters:name (str) – the environment variable name. such as ‘PATH’.
where(attrs, first=False)[source]

Return objects matching child objects properties.

Parameters:attrs (dict) – tmux properties to match values of
Returns:
Return type:list
switch_client(target_session)[source]

$ tmux switch-client.

Parameters:target_session (str) – name of the session. fnmatch(3) works.
Raises:exc.BadSessionName
attach_session(target_session=None)[source]

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

Parameters:target_session (str) – name of the session. fnmatch(3) works.
Raises:exc.BadSessionName
new_session(session_name=None, kill_session=False, attach=False, start_directory=None, window_name=None, window_command=None, *args, **kwargs)[source]

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 (str, optional) –
    $ tmux new-session -s <session_name>
    
  • attach (bool, optional) –

    create session in the foreground. attach=False is equivalent to:

    $ tmux new-session -d
    
Other Parameters:
 
  • kill_session (bool, optional) – Kill current session if $ tmux has-session. Useful for testing workspaces.

  • start_directory (str, 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) – 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.

Returns:

Return type:

Session

Raises:

exc.BadSessionName

Session Object

class libtmux.Session(server=None, **kwargs)[source]

Bases: libtmux.common.TmuxMappingObject, libtmux.common.TmuxRelationalObject, libtmux.common.EnvironmentMixin

A tmux(1) session [3].

Holds Window objects.

Parameters:server (Server) –

References

[3]
tmux session. openbsd manpage for TMUX(1).

“When tmux is started it creates a new session with a single window and displays it on screen…”

“A session is a single collection of pseudo terminals under the management of tmux. Each session has one or more windows linked to it.”

https://man.openbsd.org/tmux.1#DESCRIPTION. Accessed April 1st, 2018.

child_id_attribute = u'window_id'

unique child ID key for TmuxRelationalObject

formatter_prefix = u'session_'

namespace used TmuxMappingObject

cmd(*args, **kwargs)[source]

Return server.cmd().

Returns:
Return type:server.cmd

Notes

Changed in version 0.8: Renamed from .tmux to .cmd.

attach_session()[source]

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

kill_session()[source]

$ tmux kill-session.

switch_client()[source]

Switch client to this session.

Raises:exc.LibTmuxException
rename_session(new_name)[source]

Rename session and return new Session object.

Parameters:new_name (str) – new session name
Returns:
Return type:Session
Raises:exc.BadSessionName
new_window(window_name=None, start_directory=None, attach=True, window_index=u'', window_shell=None)[source]

Return Window from $ tmux new-window.

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 (str, optional) –
  • start_directory (str, optional) – working directory in which the new window is created.
  • attach (bool, optional) – make new window the current window after creating it, default True.
  • window_index (str) – create the new window at the given index position. Default is empty string which will create the window in the next available position.
  • window_shell (str) –

    execute a command on starting the window. 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.

Returns:

Return type:

Window

kill_window(target_window=None)[source]

Close a tmux window, and all panes inside it, $ 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 (str, optional) – window to kill
_windows

Property / alias to return Session._list_windows().

list_windows()[source]

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

Returns:
Return type:Window
windows

Property / alias to return Session.list_windows().

children

Alias windows for TmuxRelationalObject

attached_window

Return active Window object.

Returns:
Return type:Window
select_window(target_window)[source]

Return Window selected via $ tmux select-window.

Parameters:window (str) – target_window also ‘last-window’ (-l), ‘next-window’ (-n), or ‘previous-window’ (-p)
Returns:
Return type:Window

Notes

attached_pane

Return active Pane object.

set_option(option, value, _global=False)[source]

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

Parameters:
  • option (str) – the window option. such as ‘default-shell’.
  • value (str, int, or bool) – True/False will turn in ‘on’ and ‘off’. You can also enter ‘on’ or ‘off’ directly.
  • _global (bool, optional) – check for option globally across all servers (-g)
Raises:

Notes

show_options(option=None, _global=False)[source]

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 (str, optional) – name of option, e.g. ‘visual-silence’. Defaults to None, which returns all options.
  • _global (bool, optional) – Pass -g flag for global variable (server-wide)
Returns:

Return type:

dict

Notes

Uses _global for keyword name instead of global to avoid colliding with reserved keyword.

show_option(option, _global=False)[source]

Return a list of options for the window.

Parameters:
  • option (str) – option name
  • _global (bool, optional) – use global option scope, same as -g
Returns:

Return type:

str, int, or bool

Raises:

Notes

Uses _global for keyword name instead of global to avoid colliding with reserved keyword.

Test and return True/False for on/off string.

clear() → None. Remove all items from D.[source]
find_where(attrs)[source]

Return object on first match.

Changed in version 0.4: Renamed from .findWhere to .find_where.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.[source]
get_by_id(id)[source]

Return object based on child_id_attribute.

Parameters:val (str) –
Returns:
Return type:object

Notes

Based on .get() from backbone.js.

items() → list of D's (key, value) pairs, as 2-tuples[source]
iteritems() → an iterator over the (key, value) items of D[source]
iterkeys() → an iterator over the keys of D[source]
itervalues() → an iterator over the values of D[source]
keys()[source]

Return list of keys.

pop(k[, d]) → v, remove specified key and return the corresponding value.[source]

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() → (k, v), remove and return some (key, value) pair[source]

as a 2-tuple; but raise KeyError if D is empty.

remove_environment(name)[source]

Remove environment variable $ tmux set-environment -r <name>.

Parameters:name (str) – the environment variable name. such as ‘PATH’.
set_environment(name, value)[source]

Set environment $ tmux set-environment <name> <value>.

Parameters:
  • name (str) – the environment variable name. such as ‘PATH’.
  • option (str) – environment value.
setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D[source]
show_environment(name=None)[source]

Show environment $ tmux show-environment -t [session] <name>.

Return dict of environment variables for the session or the value of a specific variable if the name is specified.

Parameters:name (str) – the environment variable name. such as ‘PATH’.
Returns:environmental variables in dict, if no name, or str if name entered.
Return type:str or dict
unset_environment(name)[source]

Unset environment variable $ tmux set-environment -u <name>.

Parameters:name (str) – the environment variable name. such as ‘PATH’.
update([E, ]**F) → None. Update D from mapping/iterable E and F.[source]

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() → list of D's values[source]
where(attrs, first=False)[source]

Return objects matching child objects properties.

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

Window Object

class libtmux.Window(session=None, **kwargs)[source]

Bases: libtmux.common.TmuxMappingObject, libtmux.common.TmuxRelationalObject

A tmux(1) window [4].

Holds Pane objects.

Parameters:session (Session) –

References

[4]
tmux window. openbsd manpage for TMUX(1).
“Each session has one or more windows linked to it. A window occupies the entire screen and may be split into rectangular panes…”

https://man.openbsd.org/tmux.1#DESCRIPTION. Accessed April 1st, 2018.

child_id_attribute = u'pane_id'

unique child ID key for TmuxRelationalObject

formatter_prefix = u'window_'

namespace used TmuxMappingObject

cmd(cmd, *args, **kwargs)[source]

Return Server.cmd() 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.

Returns:
Return type:Server.cmd

Notes

Changed in version 0.8: Renamed from .tmux to .cmd.

select_layout(layout=None)[source]

Wrapper for $ tmux select-layout <layout>.

Parameters:layout (str, optional) –

string of the layout, ‘even-horizontal’, ‘tiled’, etc. Entering None (leaving this blank) is same as select-layout with no layout. In recent tmux versions, it picks the most recently set 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).
set_window_option(option, value)[source]

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

Parameters:
  • option (str) – option to set, e.g. ‘aggressive-resize’
  • value (str) – window option value. True/False will turn in ‘on’ and ‘off’, also accepts string of ‘on’ or ‘off’ directly.
Raises:
show_window_options(option=None, g=False)[source]

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 (str, optional) – show a single option.
  • g (str, optional) – Pass -g flag for global variable, default False.
Returns:

Return type:

dict

show_window_option(option, g=False)[source]

Return a list of options for the window.

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

Parameters:
  • option (str) –
  • g (bool, optional) – Pass -g flag, global. Default False.
Returns:

Return type:

str, int

Raises:
rename_window(new_name)[source]

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

Parameters:new_name (str) – name of the window
kill_window()[source]

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

move_window(destination=u'', session=None)[source]

Move the current Window object $ tmux move-window.

Parameters:
  • destination (str, optional) – the target window or index to move the window to, default: empty string
  • session (str, optional) – the target session or index to move the window to, default: current session.
select_window()[source]

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.

Returns:
Return type:Window
select_pane(target_pane)[source]

Return selected Pane through $ tmux select-pane.

Parameters:target_pane (str) – ‘target_pane’, ‘-U’ ,’-D’, ‘-L’, ‘-R’, or ‘-l’.
Returns:
Return type:Pane
last_pane()[source]

Return last pane.

split_window(target=None, start_directory=None, attach=True, vertical=True, shell=None)[source]

Split window and return the created Pane.

Used for splitting window and holding in a python object.

Parameters:
  • attach (bool, optional) – make new window the current window after creating it, default True.
  • start_directory (str, optional) – specifies the working directory in which the new window is created.
  • target (str) – target_pane to split.
  • vertical (str) – split vertically
  • shell (str, optional) –

    execute a command on splitting the window. The pane will close when the command exits.

    NOTE: When this command exits the pane will close. This feature is useful for long-running processes where the closing of the window upon completion is desired.

Returns:

Return type:

Pane

Notes

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.

attached_pane

Return the attached Pane.

Returns:
Return type:Pane
_panes

Property / alias to return _list_panes().

list_panes()[source]

Return list of Pane for the window.

Returns:
Return type:list of Pane
panes

Property / alias to return list_panes().

children

Alias panes for TmuxRelationalObject

clear() → None. Remove all items from D.[source]
find_where(attrs)[source]

Return object on first match.

Changed in version 0.4: Renamed from .findWhere to .find_where.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.[source]
get_by_id(id)[source]

Return object based on child_id_attribute.

Parameters:val (str) –
Returns:
Return type:object

Notes

Based on .get() from backbone.js.

items() → list of D's (key, value) pairs, as 2-tuples[source]
iteritems() → an iterator over the (key, value) items of D[source]
iterkeys() → an iterator over the keys of D[source]
itervalues() → an iterator over the values of D[source]
keys()[source]

Return list of keys.

pop(k[, d]) → v, remove specified key and return the corresponding value.[source]

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() → (k, v), remove and return some (key, value) pair[source]

as a 2-tuple; but raise KeyError if D is empty.

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D[source]
update([E, ]**F) → None. Update D from mapping/iterable E and F.[source]

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() → list of D's values[source]
where(attrs, first=False)[source]

Return objects matching child objects properties.

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

Pane Object

class libtmux.Pane(window=None, **kwargs)[source]

Bases: libtmux.common.TmuxMappingObject, libtmux.common.TmuxRelationalObject

A tmux(1) pane [5].

Pane instances can send commands directly to a pane, or traverse between linked tmux objects.

Parameters:window (Window) –

Notes

Changed in version 0.8: Renamed from .tmux to .cmd.

References

[5]
tmux pane. openbsd manpage for TMUX(1).
“Each window displayed by tmux may be split into one or more panes; each pane takes up a certain area of the display and is a separate terminal.”

https://man.openbsd.org/tmux.1#WINDOWS_AND_PANES. Accessed April 1st, 2018.

formatter_prefix = u'pane_'

namespace used TmuxMappingObject

cmd(cmd, *args, **kwargs)[source]

Return Server.cmd() 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.

Returns:
Return type:Server.cmd
send_keys(cmd, enter=True, suppress_history=True)[source]

$ tmux send-keys to the pane.

A leading space character is added to cmd to avoid polluting the user’s history.

Parameters:
  • cmd (str) – Text or input into pane
  • enter (bool, optional) – Send enter after sending the input, default True.
  • suppress_history (bool, optional) – Don’t add these keys to the shell history, default True.
display_message(cmd, get_text=False)[source]

$ tmux display-message to the pane.

Displays a message in target-client status line.

Parameters:
  • cmd (str) – Special parameters to request from pane.
  • get_text (bool, optional) – Returns only text without displaying a message in target-client status line.
Returns:

clear()[source]

Clear pane.

reset()[source]

Reset and clear pane history.

split_window(attach=False, vertical=True, start_directory=None)[source]

Split window at pane and return newly created Pane.

Parameters:
  • attach (bool, optional) – Attach / select pane after creation.
  • vertical (bool, optional) – split vertically
  • start_directory (str, optional) – specifies the working directory in which the new pane is created.
Returns:

Return type:

Pane

set_width(width)[source]

Set width of pane.

Parameters:width (int) – pane width, in cells
set_height(height)[source]

Set height of pane.

Parameters:height (int) – height of pain, in cells
resize_pane(*args, **kwargs)[source]

$ tmux resize-pane of pane and return self.

Parameters:

target_pane (str) – target_pane, or -U,``-D``, -L, -R.

Other Parameters:
 
  • height (int) – resize-pane -y dimensions
  • width (int) – resize-pane -x dimensions
Returns:

Return type:

Pane

Raises:

exc.LibTmuxException

enter()[source]

Send carriage return to pane.

$ tmux send-keys send Enter to the pane.

capture_pane()[source]

Capture text from pane.

$ tmux capture-pane to pane.

Returns:
Return type:list
select_pane()[source]

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.

Returns:
Return type:pane
find_where(attrs)[source]

Return object on first match.

Changed in version 0.4: Renamed from .findWhere to .find_where.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.[source]
get_by_id(id)[source]

Return object based on child_id_attribute.

Parameters:val (str) –
Returns:
Return type:object

Notes

Based on .get() from backbone.js.

items() → list of D's (key, value) pairs, as 2-tuples[source]
iteritems() → an iterator over the (key, value) items of D[source]
iterkeys() → an iterator over the keys of D[source]
itervalues() → an iterator over the values of D[source]
keys()[source]

Return list of keys.

pop(k[, d]) → v, remove specified key and return the corresponding value.[source]

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() → (k, v), remove and return some (key, value) pair[source]

as a 2-tuple; but raise KeyError if D is empty.

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D[source]
update([E, ]**F) → None. Update D from mapping/iterable E and F.[source]

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() → list of D's values[source]
where(attrs, first=False)[source]

Return objects matching child objects properties.

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

Internals

libtmux.common.TMUX_MIN_VERSION = '1.8'

Minimum version of tmux required to run libtmux

libtmux.common.TMUX_MAX_VERSION = '2.4'

Most recent version of tmux supported

class libtmux.common.TmuxRelationalObject[source]

Base Class for managing tmux object child entities. .. # NOQA

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.child_id_attribute.

Object .children method
Server Server._sessions Server.list_sessions()
Session Session._windows Session.list_windows()
Window Window._panes Window.list_panes()
Pane n/a n/a
Object child_id_attribute value
Server Server.child_id_attribute session_id
Session Session.child_id_attribute window_id
Window Window.child_id_attribute pane_id
Pane n/a n/a
find_where(attrs)[source]

Return object on first match.

Changed in version 0.4: Renamed from .findWhere to .find_where.

get_by_id(id)[source]

Return object based on child_id_attribute.

Parameters:val (str) –
Returns:
Return type:object

Notes

Based on .get() from backbone.js.

where(attrs, first=False)[source]

Return objects matching child objects properties.

Parameters:attrs (dict) – tmux properties to match values of
Returns:
Return type:list
class libtmux.common.TmuxMappingObject[source]

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._info. For example, a Window will have a window_id and window_name.

Object formatter_prefix value
Server n/a n/a
Session Session.formatter_prefix session_
Window Window.formatter_prefix window_
Pane Pane.formatter_prefix pane_
keys()[source]

Return list of keys.

class libtmux.common.EnvironmentMixin(add_option=None)[source]

Mixin class for managing session and server level environment variables in tmux.

remove_environment(name)[source]

Remove environment variable $ tmux set-environment -r <name>.

Parameters:name (str) – the environment variable name. such as ‘PATH’.
set_environment(name, value)[source]

Set environment $ tmux set-environment <name> <value>.

Parameters:
  • name (str) – the environment variable name. such as ‘PATH’.
  • option (str) – environment value.
show_environment(name=None)[source]

Show environment $ tmux show-environment -t [session] <name>.

Return dict of environment variables for the session or the value of a specific variable if the name is specified.

Parameters:name (str) – the environment variable name. such as ‘PATH’.
Returns:environmental variables in dict, if no name, or str if name entered.
Return type:str or dict
unset_environment(name)[source]

Unset environment variable $ tmux set-environment -u <name>.

Parameters:name (str) – the environment variable name. such as ‘PATH’.
class libtmux.common.tmux_cmd(*args, **kwargs)[source]

tmux(1) command via subprocess.

Parameters:
  • tmux_search_paths (list, optional) – Default PATHs to search tmux for, defaults to default_paths used in which().
  • append_env_path (bool) – Append environment PATHs to tmux search paths. True by default.

Examples

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

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

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

Equivalent to:

$ tmux new-session -s my session

Notes

Changed in version 0.8: Renamed from tmux to tmux_cmd.

common.which(default_paths=['/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin'], append_env_path=True)[source]

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

Parameters:
  • exe (str) – Application to search PATHs for.
  • default_paths (list) – Paths to check inside of
  • append_env_path (bool, optional) – Append list of directories to check in from PATH environment variable. Default True. Setting False only for testing / diagnosing.
Returns:

path of application, if found in paths.

Return type:

str

Notes

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

common.get_version()[source]

Return tmux version.

If tmux is built from git master, the version returned will be the latest version appended with -master, e.g. 2.4-master.

If using OpenBSD’s base system tmux, the version will have -openbsd appended to the latest version, e.g. 2.4-openbsd.

Returns:tmux version according to libtmux.common.which()’s tmux
Return type:distutils.version.LooseVersion
common.has_version()[source]

Return affirmative if tmux version installed.

Parameters:version (str) – version number, e.g. ‘1.8’
Returns:True if version matches
Return type:bool
common.has_gt_version()[source]

Return affirmative if tmux version greater than minimum.

Parameters:min_version (str) – tmux version, e.g. ‘1.8’
Returns:True if version above min_version
Return type:bool
common.has_gte_version()[source]

Return True if tmux version greater or equal to minimum.

Parameters:min_version (str) – tmux version, e.g. ‘1.8’
Returns:True if version above or equal to min_version
Return type:bool
common.has_lt_version()[source]

Return True if tmux version less than minimum.

Parameters:max_version (str) – tmux version, e.g. ‘1.8’
Returns:True if version below max_version
Return type:bool
common.has_lte_version()[source]

Return True if tmux version less or equal to minimum.

Parameters:max_version (str) – tmux version, e.g. ‘1.8’
Returns:True if version below or equal to max_version
Return type:bool
common.has_minimum_version()[source]

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

Parameters:raises (bool) – raise exception if below minimum version requirement
Returns:True if tmux meets minimum required version.
Return type:bool
Raises:libtmux.exc.VersionTooLow – tmux version below minimum required for libtmux

Notes

Changed in version 0.7.0: No longer returns version, returns True or False

Changed in version 0.1.7: Versions will now remove trailing letters per Issue 55.

common.handle_option_error()[source]

Raises exception if error in option command found.

Purpose: As of tmux 2.4, there are now 3 different types of option errors:

  • unknown option
  • invalid option
  • ambiguous option

Before 2.4, unknown option was the user.

All errors raised will have the base error of exc.OptionError. So to catch any option error, use except exc.OptionError.

Parameters:

error (str) – Error response from subprocess call.

Raises:

Exceptions

exception libtmux.exc.LibTmuxException[source]

Base Exception for libtmux Errors.

exception libtmux.exc.TmuxCommandNotFound[source]

Application binary for tmux not found.

exception libtmux.exc.VersionTooLow[source]

Raised if tmux below the minimum version to use libtmux.

exception libtmux.exc.TmuxSessionExists[source]

Session does not exist in the server.

exception libtmux.exc.BadSessionName[source]

Disallowed session name for tmux (empty, contains periods or colons).

exception libtmux.exc.OptionError[source]

Root error for any error involving invalid, ambiguous or bad options.

exception libtmux.exc.UnknownOption[source]

Option unknown to tmux show-option(s) or show-window-option(s).

exception libtmux.exc.InvalidOption[source]

Option invalid to tmux, introduced in tmux v2.4.

exception libtmux.exc.AmbiguousOption[source]

Option that could potentially match more than one.

Test tools

test.retry()[source]

Retry a block of code until a time limit or break.

Parameters:seconds (int) – Seconds to retry, defaults to RETRY_TIMEOUT_SECONDS, which is configurable via environmental variables.
Returns:True if time passed since retry() invoked less than seconds param.
Return type:bool

Examples

>>> while retry():
...      p = w.attached_pane
...      p.server._update_panes()
...      if p.current_path == pane_path:
...          break
test.get_test_session_name(prefix=u'libtmux_')[source]

Faker to create a session name that doesn’t exist.

Parameters:
  • server (libtmux.Server) – libtmux server
  • prefix (str) – prefix for sessions (e.g. libtmux_). Defaults to TEST_SESSION_PREFIX.
Returns:

Random session name guaranteed to not collide with current ones.

Return type:

str

test.get_test_window_name(prefix=u'libtmux_')[source]

Faker to create a window name that doesn’t exist.

Parameters:
  • session (libtmux.Session) – libtmux session
  • prefix (str) –

    prefix for windows (e.g. libtmux_). Defaults to TEST_SESSION_PREFIX.

    ATM we reuse the test session prefix here.

Returns:

Random window name guaranteed to not collide with current ones.

Return type:

str

test.temp_session(**kwds)[source]

Return a context manager with a temporary session.

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

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

Parameters:

server (libtmux.Server) –

Other Parameters:
 
Yields:

libtmux.Session – Temporary session

Examples

>>> with temp_session(server) as session:
...     session.new_window(window_name='my window')
test.temp_window(**kwds)[source]

Return a context manager with a temporary 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.

Parameters:

session (libtmux.Session) –

Other Parameters:
 
Yields:

libtmux.Window – temporary window

Examples

>>> with temp_window(session) as window:
...     my_pane = window.split_window()
class libtmux.test.EnvironmentVarGuard[source]

Mock environmental variables safetly.

Helps rotect the environment variable properly. Can be used as context manager.

Notes

Vendorized to fix issue with Anaconda Python 2 not including test module, see #121 [1]

References

[1]Just installed, “ImportError: cannot import name test_support”. GitHub issue for tmuxp. https://github.com/tmux-python/tmuxp/issues/121. Created October 12th, 2015. Accessed April 7th, 2018.