Upload
hakhanh
View
257
Download
6
Embed Size (px)
Citation preview
libtmux DocumentationRelease 0.8.0
Tony Narlock
May 06, 2018
Contents
1 install 3
2 open a tmux session 5
3 pilot your tmux session via python 7
4 Donations 114.1 Quickstart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114.2 About . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154.3 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174.4 Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204.5 Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214.6 Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264.7 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304.8 Panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344.9 API Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374.10 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594.11 Developing and Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604.12 History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Python Module Index 67
i
ii
libtmux Documentation, Release 0.8.0
libtmux is the tool behind tmuxp, a tmux workspace manager in python.
it builds upon tmux’s target and formats to create an object mapping to traverse, inspect and interact with live tmuxsessions.
view the documentation homepage, API information and architectural details.
Contents 1
libtmux Documentation, Release 0.8.0
2 Contents
CHAPTER 1
install
$ [sudo] pip install libtmux
3
libtmux Documentation, Release 0.8.0
4 Chapter 1. install
CHAPTER 2
open a tmux session
session name foo, window name bar
$ tmux new-session -s foo -n bar
5
libtmux Documentation, Release 0.8.0
6 Chapter 2. open a tmux session
CHAPTER 3
pilot your tmux session via python
$ python
# or for nice autocomplete and syntax highlighting$ pip install ptpython$ ptpython
connect to a live tmux session:
>>> import libtmux>>> server = libtmux.Server()>>> server<libtmux.server.Server object at 0x7fbd622c1dd0>
list sessions:
>>> server.list_sessions()[Session($3 foo), Session($1 libtmux)]
find session:
>>> server.get_by_id('$3')Session($3 foo)
find session by dict lookup:
>>> server.find_where({ "session_name": "foo" })Session($3 foo)
assign session to session:
>>> session = server.find_where({ "session_name": "foo" })
play with session:
7
libtmux Documentation, Release 0.8.0
>>> session.new_window(attach=False, window_name="ha in the bg")Window(@8 2:ha in the bg, Session($3 foo))>>> session.kill_window("ha in")
create new window in the background (don’t switch to it):
>>> w = session.new_window(attach=False, window_name="ha in the bg")Window(@11 3:ha in the bg, Session($3 foo))
kill window object directly:
>>> w.kill_window()
grab remaining tmux window:
>>> window = session.attached_window>>> window.split_window(attach=False)Pane(%23 Window(@10 1:bar, Session($3 foo)))
rename window:
>>> window.rename_window('libtmuxower')Window(@10 1:libtmuxower, Session($3 foo))
create panes by splitting window:
>>> pane = window.split_window()>>> pane = window.split_window(attach=False)>>> pane.select_pane()>>> window = session.new_window(attach=False, window_name="test")>>> pane = window.split_window(attach=False)
send key strokes to panes:
>>> pane.send_keys('echo hey send now')
>>> pane.send_keys('echo hey', enter=False)>>> pane.enter()
grab the output of pane:
>>> pane.clear() # clear the pane>>> pane.send_keys('cowsay hello')>>> print('\n'.join(pane.cmd('capture-pane', '-p').stdout))
sh-3.2$ cowsay 'hello'_______
< hello >-------
\ ^__^\ (oo)\_______
(__)\ )\/\||----w ||| ||
powerful traversal features:
8 Chapter 3. pilot your tmux session via python
libtmux Documentation, Release 0.8.0
>>> pane.windowWindow(@10 1:libtmuxower, Session($3 foo))>>> pane.window.sessionSession($3 foo)
9
libtmux Documentation, Release 0.8.0
10 Chapter 3. pilot your tmux session via python
CHAPTER 4
Donations
Your donations fund development of new features, testing and support. Your money will go directly to maintenanceand development of the project. If you are an individual, feel free to give whatever feels right for the value you get outof the project.
See donation options at https://git-pull.com/support.html.
Explore:
4.1 Quickstart
libtmux allows for developers and system administrators to control live tmux sessions using python code.
In this example, we will launch a tmux session and control the windows from inside a live tmux session.
4.1.1 Requirements
• tmux
• pip - for this handbook’s examples
4.1.2 Installation
Next, ensure libtmux is installed:
$ [sudo] pip install libtmux
4.1.3 Start a tmux session
Now, let’s open a tmux session.
11
libtmux Documentation, Release 0.8.0
$ tmux new-session -n bar -s foo
This tutorial will be using the session and window name in the example.
Window name -n: bar Session name -s: foo
4.1.4 Control tmux via python
See also:
API Reference
$ python
For commandline completion, you can also use ptpython.
$ [sudo] pip install ptpython$ ptpython
First, we can grab a Server.
>>> import libtmux>>> server = libtmux.Server()>>> server<libtmux.server.Server object at 0x7fbd622c1dd0>
Note: You can specify a socket_name, socket_path and config_file in your server object. libtmux.Server(socket_name='mysocket') is equivalent to $ tmux -L mysocket.
server is now a living object bound to the tmux server’s Sessions, Windows and Panes.
4.1.5 Find your Session
If you have multiple tmux sessions open, you can see that all of the methods in Server are available.
We can list sessions with Server.list_sessions():
>>> server.list_sessions()[Session($3 foo), Session($1 libtmux)]
This returns a list of Session objects you can grab. We can find our current session with:
>>> server.list_sessions()[0]
However, this isn’t guaranteed, libtmux works against current tmux information, the session’s name could be changed,or another tmux session may be created, so Server.get_by_id() and Server.find_where() exists as alookup.
4.1.6 Get session by ID
tmux sessions use the $[0-9] convention as a way to identify sessions.
$3 is whatever the ID list_sessions() returned above.
12 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
>>> server.get_by_id('$3')Session($3 foo)
You may session = server.get_by_id('$<yourId>') to use the session object.
4.1.7 Get session by name / other properties
>>> server.find_where({ "session_name": "foo" })Session($3 foo)
With find_where, pass in a dict and return the first object found. In this case, a Server holds a collection of childSession. Session and Window both utilize find_where to sift through Windows and Panes, respectively.
So you may now use:
>>> session = server.find_where({ "session_name": "foo" })
to give us a session object to play with.
4.1.8 Playing with our tmux session
We now have access to session from above with all of the methods available in Session.
Let’s make a Session.new_window(), in the background:
>>> session.new_window(attach=False, window_name="ha in the bg")Window(@8 2:ha in the bg, Session($3 foo))
So a few things:
1. attach=False meant to create a new window, but not to switch to it. It is the same as $ tmuxnew-window -d.
2. window_name may be specified.
3. Returns the Window object created.
Note: Use the API reference API Reference for more commands.
Let’s delete that window (Session.kill_window()).
Method 1: Use passthrough to tmux’s target system.
>>> session.kill_window("ha in")
The window in the bg dissappeared. This was the equivalent of $ tmux kill-window -t'ha in'
Internally, tmux uses target. Its specific behavior depends on what the target is, view the tmux manpage for moreinformation:
This section contains a list of the commands supported by tmux. Most commandsaccept the optional -t argument with one of target-client, target-session,target-window, or target-pane.
In this case, you can also go back in time and recreate the window again. The CLI should have history, so navigate upwith the arrow key.
4.1. Quickstart 13
libtmux Documentation, Release 0.8.0
>>> session.new_window(attach=False, window_name="ha in the bg")Window(@11 3:ha in the bg, Session($3 foo))
Try to kill the window by the matching id @[0-9999].
>>> session.new_window(attach=False, window_name="ha in the bg")Window(@12 3:ha in the bg, Session($3 foo))
In addition, you could also .kill_window direction from the Window object:
>>> window = session.new_window(attach=False, window_name="check this out")
And kill:
>>> window.kill_window()
Use Session.list_windows() and Session.find_where() to list and sort through active Window’s.
4.1.9 Manipulating windows
Now that we know how to create windows, let’s use one. Let’s use Session.attached_window() to grab ourcurrent window.
>>> window = session.attached_window()
window now has access to all of the objects inside of Window .
Let’s create a pane, Window.split_window():
>>> window.split_window(attach=False)Pane(%23 Window(@10 1:bar, Session($3 foo)))
Powered up. Let’s have a break down:
1. window = session.attached_window() gave us the Window of the current attached to window.
2. attach=False assures the cursor didn’t switch to the newly created pane.
3. Returned the created Pane.
Also, since you are aware of this power, let’s commemorate the experience:
>>> window.rename_window('libtmuxower')Window(@10 1:libtmuxower, Session($3 foo))
You should have noticed Window.rename_window() renamed the window.
4.1.10 Moving cursor across windows and panes
You have two ways you can move your cursor to new sessions, windows and panes.
For one, arguments such as attach=False can be omittted.
>>> pane = window.split_window()
This gives you the Pane along with moving the cursor to a new window. You can also use the .select_* availableon the object, in this case the pane has Pane.select_pane().
14 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
>>> pane = window.split_window(attach=False)>>> pane.select_pane()
4.1.11 Sending commands to tmux panes remotely
You may send commands to panes, windows and sessions without them being visible. As long as you have the object,or are iterating through a list of them, you can use .send_keys.
>>> window = session.new_window(attach=False, window_name="test")>>> pane = window.split_window(attach=False)>>> pane.send_keys('echo hey', enter=False)
See the other window, notice that Pane.send_keys() has ” echo hey” written, still in the prompt. Note theleading space character so the command won’t be added to the user’s history. Use pane.cmd(‘send-keys’, text) to sendkeys without this leading space.
enter=False can be used to send keys without pressing return. In this case, you may leave it to the user to pressreturn himself, or complete a command using Pane.enter():
>>> pane.enter()
4.1.12 Final notes
These objects created use tmux’s internal usage of ID’s to make servers, sessions, windows and panes accessible at theobject level.
You don’t have to see the tmux session to be able to orchestrate it. After all, WorkspaceBuilder uses these sameinternals to build your sessions in the background. :)
See also:
If you want to dig deeper, check out API Reference, the code for and our test suite (see Developing and Testing.)
4.2 About
See also:
API Reference
libtmux is an abstraction layer for tmux.
It builds upon the concept of targets -t, to direct commands against individual session, windows and panes andFORMATS, template variables exposed by tmux to describe their properties. Think of -t analagously to scope.
common.TmuxRelationalObject acts as a container to connect the relations of Server, Session, Windowand Pane.
Object Child ParentServer Session NoneSession Window ServerWindow Pane SessionPane None Window
4.2. About 15
libtmux Documentation, Release 0.8.0
Internally, tmux allows multiple servers to be ran on a system. Each one uses a socket. The server-client architectureis executed so cleanly, many users don’t think about it. tmux automatically connects to a default socket name andlocation for you if none (-L, -S) is specified. A server will be created automatically upon starting if none exists.
A server can have multiple sessions. Ctrl-a s can be used to switch between sessions running on the server.
Sessions, Windows and Panes all have their own unique identifier for internal purposes. common.TmuxMappingObject will make use of the unique identifiers (session_id, window_id, pane_id ) to lookup the data stored in the Server object.
Object Prefix ExampleServer N/A N/A, uses socket-name and socket-pathSession $ $13Window @ @3243Pane % %5433
4.2.1 Similarities to tmux and Pythonics
libtmux was built in the spirit of understanding how tmux operates and how python objects and tools can abstract theAPI’s in a pleasant way.
libtmux uses FORMATTERS in tmux to give identity attributes to Session, Window and Pane objects. See format.c.
How is libtmux able to keep references to panes, windows and sessions?
Tmux has unique ID’s for sessions, windows and panes.
panes use %, such as %1234
windows use @, such as @2345
sessions use $, for money, such as $
How is libtmux able to handle windows with no names?
Tmux provides window_id as a unique identifier.
What is a {pane,window}_index vs a {pane,window,session}_id?
Pane index refers to the order of a pane on the screen.
Window index refers to the # of the window in the session.
To assert pane, window and session data, libtmux will use Server.list_sessions(), Session.list_windows(), Window.list_panes() to update objects.
4.2.2 Naming conventions
Because this is a python abstraction and commands like new-window have dashes (-) replaced with underscores (_).
4.2.3 Reference
• tmux docs http://www.openbsd.org/cgi-bin/man.cgi?query=tmux&sektion=1
• tmux source code http://sourceforge.net/p/tmux/tmux-code/ci/master/tree/
16 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
4.3 Properties
Get access to the data attributions behind tmux sessions, windows and panes.
This is done through accessing the formats available in list-sessions, list-windows and list-panes.
open two terminals:
terminal one: start tmux in a seperate terminal:
$ tmux
Note: Make sure you have libtmux installed:
pip install libtmux
To upgrade:
pip install -U libtmux
terminal two, python or ptpython if you have it:
$ python
import tmux:
import tmux
attach default tmux libtmux.Server to t:
>>> t = libtmux.Server();>>> t<libtmux.server.Server object at 0x10edd31d0>
4.3.1 Session
get the session object:
>>> session = t.sessions[0]
>>> sessionSession($0 libtmux)
quick access to basic attributes:
>>> session.nameu'libtmux'
>>> session.idu'$0'
>>> session.widthu'213'
(continues on next page)
4.3. Properties 17
libtmux Documentation, Release 0.8.0
(continued from previous page)
>>> session.heightu'114'
to see all attributes for a session:
>>> session._info.keys()[u'session_height', u'session_windows', u'session_width', u'session_id', u'session_→˓created', u'session_attached', u'session_grouped', u'session_name']
>>> session._info{u'session_height': u'114', u'session_windows': u'3', u'session_width': u'213', u→˓'session_id': u'$0', u'session_created': u'1464905357', u'session_attached': u'1', u→˓'session_grouped': u'0', u'session_name': u'libtmux'}
some may conflict with python API, to access them, you can use .get(), to get the count of sessions in a window:
>>> session.get('session_windows')u'3'
4.3.2 Windows
The same concepts apply for window:
>>> window = session.attached_window
>>> windowWindow(@2 2:docs, Session($0 libtmux))
basics:
>>> window.nameu'docs'
>>> window.idu'@2'
>>> window.heightu'114'
>>> window.widthu'213'
everything available:
>>> window._info{u'window_panes': u'4', u'window_active': u'1', u'window_height': u'114', u'window_→˓activity_flag': u'0', u'window_width': u'213', u'session_id': u'$0', u'window_id': u→˓'@2', u'window_layout': u'dad5,213x114,0,0[213x60,0,0,4,213x53,0,61{70x53,0,61,5,→˓70x53,71,61,6,71x53,142,61,7}]', u'window_silence_flag': u'0', u'window_index': u'2→˓', u'window_bell_flag': u'0', u'session_name': u'libtmux', u'window_flags': u'*', u→˓'window_name': u'docs'}
>>> window.keys()[u'window_panes', u'window_active', u'window_height', u'window_activity_flag', u→˓'window_width', u'session_id', u'window_id', u'window_layout', u'window_silence_flag→˓', u'window_index', u'window_bell_flag', u'session_name', u'window_flags', u'window_→˓name']
(continues on next page)
18 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
(continued from previous page)
use get() for details not accessible via properties:
>>> pane.get('window_panes')u'4'
4.3.3 Panes
get the pane:
>>> pane = window.attached_pane
>>> panePane(%5 Window(@2 2:docs, Session($0 libtmux)))
basics:
>>> pane.current_commandu'python'
>>> pane.heightu'53'
>>> pane.widthu'70'
>>> pane.indexu'1'
everything:
>>> pane._info{u'alternate_saved_x': u'0', u'alternate_saved_y': u'0', u'cursor_y': u'47', u'cursor_→˓x': u'0', u'pane_in_mode': u'0', u'insert_flag': u'0', u'keypad_flag': u'0', u→˓'cursor_flag': u'1', u'pane_current_command': u'python', u'window_index': u'2', u→˓'history_size': u'216', u'scroll_region_lower': u'52', u'keypad_cursor_flag': u'0',→˓u'history_bytes': u'38778', u'pane_active': u'1', u'pane_dead': u'0', u'pane_→˓synchronized': u'0', u'window_id': u'@2', u'pane_index': u'1', u'pane_width': u'70',→˓ u'mouse_any_flag': u'0', u'mouse_button_flag': u'0', u'window_name': u'docs', u→˓'pane_current_path': u'/Users/me/work/python/libtmux/doc', u'pane_tty': u'/dev/→˓ttys007', u'pane_title': u'Python REPL (ptpython)', u'session_id': u'$0', u→˓'alternate_on': u'0', u'mouse_standard_flag': u'0', u'wrap_flag': u'1', u'history_→˓limit': u'2000', u'pane_pid': u'37172', u'pane_height': u'53', u'session_name': u→˓'libtmux', u'scroll_region_upper': u'0', u'pane_id': u'%5'}
>>> pane._info.keys()[u'alternate_saved_x', u'alternate_saved_y', u'cursor_y', u'cursor_x', u'pane_in_mode→˓', u'insert_flag', u'keypad_flag', u'cursor_flag', u'pane_current_command', u→˓'window_index', u'history_size', u'scroll_region_lower', u'keypad_cursor_flag', u→˓'history_bytes', u'pane_active', u'pane_dead', u'pane_synchronized', u'window_id', u→˓'pane_index', u'pane_width', u'mouse_any_flag', u'mouse_button_flag', u'window_name→˓', u'pane_current_path', u'pane_tty', u'pane_title', u'session_id', u'alternate_on',→˓ u'mouse_standard_flag', u'wrap_flag', u'history_limit', u'pane_pid', u'pane_height→˓', u'session_name', u'scroll_region_upper', u'pane_id']
4.3. Properties 19
libtmux Documentation, Release 0.8.0
use get() for details keys:
>>> pane.get('pane_width')u'70'
4.4 Traversal
libtmux convenient access to move around the hierachy of sessions, windows and panes in tmux.
this is done by libtmux’s object abstraction of target_s (the -t command) and the permanent internal ID’s tmux givesto objects.
open two terminals:
terminal one: start tmux in a seperate terminal:
$ tmux
Note: Make sure you have libtmux installed:
$ pip install libtmux
To upgrade:
$ pip install -U libtmux
terminal two, python or ptpython if you have it:
$ python
import tmux:
import tmux
attach default tmux libtmux.Server to t:
>>> t = libtmux.Server();>>> t<libtmux.server.Server object at 0x10edd31d0>
get first session Session to session:
>>> session = t.sessions[0]>>> sessionSession($0 libtmux)
get a list of sessions:
>>> t.sessions[Session($0 libtmux), Session($1 tmuxp)]
iterate through sessions in a server:
20 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
>>> for sess in t.sessions:... print(sess)
Session($0 libtmux)Session($1 tmuxp)
grab a Window from a session:
>>> session.windows[0]Window(@1 1:libtmux, Session($0 libtmux))
grab the currently focused window from session:
>>> session.attached_windowWindow(@2 2:docs, Session($0 libtmux))
grab the currently focused Pane from session:
>>> session.attached_panePane(%5 Window(@2 2:docs, Session($0 libtmux)))
assign the attached pane to p:
>>> p = session.attached_pane
access the window/server of a pane:
>>> p.windowWindow(@2 2:docs, Session($0 libtmux))
>>> p.server<libtmux.server.Server object at 0x104191a10>
4.5 Servers
• identified by socket path and socket name
• may have >1 servers running of tmux at the same time.
• hold Sessions (which hold Windows, which hold Panes)
In tmux, a server is automatically started on your behalf when you first run tmux.
class libtmux.Server(socket_name=None, socket_path=None, config_file=None, colors=None,**kwargs)
Bases: libtmux.common.TmuxRelationalObject, libtmux.common.EnvironmentMixin
The tmux(1) server1.
• Server._sessions [Session, . . . ]
– Session._windows [Window , . . . ]1
CLIENTS AND SESSIONS. openbsd manpage for TMUX(1) “The tmux server manages clients, sessions, windows and panes. Clients areattached to sessions to interact with them, either when they are created with the new-session command, or later with the attach-sessioncommand. Each session has one or more windows linked into it. Windows may be linked to multiple sessions and are made up of one ormore panes, each of which contains a pseudo terminal.”
https://man.openbsd.org/tmux.1#CLIENTS_AND_SESSIONS. Accessed April 1st, 2018.
4.5. Servers 21
libtmux Documentation, Release 0.8.0
* Window._panes [Pane, . . . ]
· Pane
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
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)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()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
_sessionsProperty / alias to return _list_sessions().
list_sessions()Return list of Session from the tmux(1) session.
22 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
Returns
Return type list of Session
sessionsProperty / alias to return list_sessions().
childrenAlias sessions for TmuxRelationalObject
_list_windows()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()Update internal window data and return self for chainability.
Returns
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_cmd which wraps subprocess.Popen.
Returns
Return type list
_update_panes()Update internal pane data and return self for chainability.
Returns
Return type Server
attached_sessionsReturn 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)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. Inter-nally prepends = to the session in $ tmux has-session. tmux 2.1 and up only.
Raises exc.BadSessionName
Returns
4.5. Servers 23
libtmux Documentation, Release 0.8.0
Return type bool
kill_server()$ tmux kill-server.
find_where(attrs)Return object on first match.
Changed in version 0.4: Renamed from .findWhere to .find_where.
get_by_id(id)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)Kill the tmux session with $ tmux kill-session, return self.
Parameters target_session (str, optional) – target_session: str. note this acceptsfnmatch(3). ‘asdf’ will kill ‘asdfasd’.
Returns
Return type Server
Raises exc.BadSessionName
remove_environment(name)Remove environment variable $ tmux set-environment -r <name>.
Parameters name (str) – the environment variable name. such as ‘PATH’.
set_environment(name, value)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)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 isspecified.
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)Unset environment variable $ tmux set-environment -u <name>.
Parameters name (str) – the environment variable name. such as ‘PATH’.
24 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
where(attrs, first=False)Return objects matching child objects properties.
Parameters attrs (dict) – tmux properties to match values of
Returns
Return type list
switch_client(target_session)$ tmux switch-client.
Parameters target_session (str) – name of the session. fnmatch(3) works.
Raises exc.BadSessionName
attach_session(target_session=None)$ 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, win-dow_name=None, window_command=None, *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 -Adwill 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 isequivalent to:
$ tmux new-session -d
Other Parameters
• kill_session (bool, optional) – Kill current session if $ tmux has-session. Usefulfor testing workspaces.
• start_directory (str, optional) – specifies the working directory in which the new sessionis created.
• window_name (str, optional) –
$ tmux new-session -n <window_name>
• window_command (str) – execute a command on starting the session. The window willclose 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 uponcompletion is desired.
Returns
Return type Session
Raises exc.BadSessionName
4.5. Servers 25
libtmux Documentation, Release 0.8.0
4.6 Sessions
• exist inside Servers
• contain Windows (which hold Panes)
• identified by $, e.g. $313
class libtmux.Session(server=None, **kwargs)Bases: libtmux.common.TmuxMappingObject, libtmux.common.TmuxRelationalObject,libtmux.common.EnvironmentMixin
A tmux(1) session1.
Holds Window objects.
Parameters server (Server) –
References
child_id_attribute = u'window_id'unique child ID key for TmuxRelationalObject
formatter_prefix = u'session_'namespace used TmuxMappingObject
cmd(*args, **kwargs)Return server.cmd().
Returns
Return type server.cmd
Notes
Changed in version 0.8: Renamed from .tmux to .cmd.
attach_session()Return $ tmux attach-session aka alias: $ tmux attach.
kill_session()$ tmux kill-session.
switch_client()Switch client to this session.
Raises exc.LibTmuxException
rename_session(new_name)Rename session and return new Session object.
Parameters new_name (str) – new session name
Returns
Return type Session
1
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.
26 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
Raises exc.BadSessionName
new_window(window_name=None, start_directory=None, attach=True, window_index=u”, win-dow_shell=None)
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 win-dow 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 isempty string which will create the window in the next available position.
• window_shell (str) – execute a command on starting the window. The window willclose 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)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 itis linked.
Parameters target_window (str, optional) – window to kill
_windowsProperty / alias to return Session._list_windows().
list_windows()Return a list of Window from the tmux(1) session.
Returns
Return type Window
windowsProperty / alias to return Session.list_windows().
childrenAlias windows for TmuxRelationalObject
attached_windowReturn active Window object.
Returns
Return type Window
4.6. Sessions 27
libtmux Documentation, Release 0.8.0
select_window(target_window)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_paneReturn active Pane object.
set_option(option, value, _global=False)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 alsoenter ‘on’ or ‘off’ directly.
• _global (bool, optional) – check for option globally across all servers (-g)
Raises
• exc.OptionError, exc.UnknownOption,
• exc.InvalidOption, exc.AmbiguousOption
Notes
show_options(option=None, _global=False)Return a dict of options for the window.
For familiarity with tmux, the option option param forwards to pick a single option, forwarding toSession.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)Return a list of options for the window.
Parameters
28 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
• option (str) – option name
• _global (bool, optional) – use global option scope, same as -g
Returns
Return type str, int, or bool
Raises
• exc.OptionError, exc.UnknownOption,
• exc.InvalidOption, exc.AmbiguousOption
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.
find_where(attrs)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.
get_by_id(id)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
iteritems()→ an iterator over the (key, value) items of D
iterkeys()→ an iterator over the keys of D
itervalues()→ an iterator over the values of D
keys()Return list of keys.
pop(k[, d ])→ v, remove specified key and return the corresponding value.If key is not found, d is returned if given, otherwise KeyError is raised.
popitem()→ (k, v), remove and return some (key, value) pairas a 2-tuple; but raise KeyError if D is empty.
remove_environment(name)Remove environment variable $ tmux set-environment -r <name>.
Parameters name (str) – the environment variable name. such as ‘PATH’.
4.6. Sessions 29
libtmux Documentation, Release 0.8.0
set_environment(name, value)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
show_environment(name=None)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 isspecified.
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)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.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
where(attrs, first=False)Return objects matching child objects properties.
Parameters attrs (dict) – tmux properties to match values of
Returns
Return type list
4.7 Windows
• exist inside Sessions
• contain Panes
• identified by @, e.g. @313
class libtmux.Window(session=None, **kwargs)Bases: libtmux.common.TmuxMappingObject, libtmux.common.TmuxRelationalObject
A tmux(1) window1.
Holds Pane objects.
Parameters session (Session) –1
tmux window. openbsd manpage for TMUX(1). “Each session has one or more windows linked to it. A window occupies the entire screen andmay be split into rectangular panes. . . ”
https://man.openbsd.org/tmux.1#DESCRIPTION. Accessed April 1st, 2018.
30 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
References
child_id_attribute = u'pane_id'unique child ID key for TmuxRelationalObject
formatter_prefix = u'window_'namespace used TmuxMappingObject
cmd(cmd, *args, **kwargs)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 usingthe 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)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 recenttmux 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 remainingpanes 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 theothers 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)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 acceptsstring of ‘on’ or ‘off’ directly.
Raises
• exc.OptionError, exc.UnknownOption,
• exc.InvalidOption, exc.AmbiguousOption
4.7. Windows 31
libtmux Documentation, Release 0.8.0
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 toWindow.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)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
• exc.OptionError, exc.UnknownOption,
• exc.InvalidOption, exc.AmbiguousOption
rename_window(new_name)Return Window object $ tmux rename-window <new_name>.
Parameters new_name (str) – name of the window
kill_window()Kill the current Window object. $ tmux kill-window.
move_window(destination=u”, session=None)Move the current Window object $ tmux move-window.
Parameters
• destination (str, optional) – the target window or index to move the win-dow to, default: empty string
• session (str, optional) – the target session or index to move the windowto, default: current session.
select_window()Select window. Return self.
To select a window object asynchrously. If a window object exists and is no longer longer the currentwindow, w.select_window() will make w the current window.
Returns
Return type Window
select_pane(target_pane)Return selected Pane through $ tmux select-pane.
32 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
Parameters target_pane (str) – ‘target_pane’, ‘-U’ ,’-D’, ‘-L’, ‘-R’, or ‘-l’.
Returns
Return type Pane
last_pane()Return last pane.
split_window(target=None, start_directory=None, attach=True, vertical=True, shell=None)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 whichthe 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 panewill 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 andsplit the pane in another target window, pass in attach=False.
attached_paneReturn the attached Pane.
Returns
Return type Pane
_panesProperty / alias to return _list_panes().
list_panes()Return list of Pane for the window.
Returns
Return type list of Pane
panesProperty / alias to return list_panes().
4.7. Windows 33
libtmux Documentation, Release 0.8.0
childrenAlias panes for TmuxRelationalObject
clear()→ None. Remove all items from D.
find_where(attrs)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.
get_by_id(id)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
iteritems()→ an iterator over the (key, value) items of D
iterkeys()→ an iterator over the keys of D
itervalues()→ an iterator over the values of D
keys()Return list of keys.
pop(k[, d ])→ v, remove specified key and return the corresponding value.If key is not found, d is returned if given, otherwise KeyError is raised.
popitem()→ (k, v), remove and return some (key, value) pairas 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
update([E ], **F)→ None. Update D from mapping/iterable E and F.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
where(attrs, first=False)Return objects matching child objects properties.
Parameters attrs (dict) – tmux properties to match values of
Returns
Return type list
4.8 Panes
• hold pseudoterminal’s (pty(4))
34 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
• exist inside Windows
• identified by %, e.g. %313
class libtmux.Pane(window=None, **kwargs)Bases: libtmux.common.TmuxMappingObject, libtmux.common.TmuxRelationalObject
A tmux(1) pane1.
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
formatter_prefix = u'pane_'namespace used TmuxMappingObject
cmd(cmd, *args, **kwargs)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 usingthe object’s pane_id as target.
Returns
Return type Server.cmd
send_keys(cmd, enter=True, suppress_history=True)$ 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.
clear()Clear pane.
reset()Reset and clear pane history.
split_window(attach=False, vertical=True, start_directory=None)Split window at pane and return newly created Pane.
Parameters1
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 certainarea of the display and is a separate terminal.”
https://man.openbsd.org/tmux.1#WINDOWS_AND_PANES. Accessed April 1st, 2018.
4.8. Panes 35
libtmux Documentation, Release 0.8.0
• attach (bool, optional) – Attach / select pane after creation.
• vertical (bool, optional) – split vertically
• start_directory (str, optional) – specifies the working directory in whichthe new pane is created.
Returns
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) – height of pain, in cells
resize_pane(*args, **kwargs)$ 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()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 currentwindow, w.select_pane() will make p the current pane.
Returns
Return type pane
find_where(attrs)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.
get_by_id(id)Return object based on child_id_attribute.
Parameters val (str) –
Returns
Return type object
36 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
Notes
Based on .get() from backbone.js.
items()→ list of D’s (key, value) pairs, as 2-tuples
iteritems()→ an iterator over the (key, value) items of D
iterkeys()→ an iterator over the keys of D
itervalues()→ an iterator over the values of D
keys()Return list of keys.
pop(k[, d ])→ v, remove specified key and return the corresponding value.If key is not found, d is returned if given, otherwise KeyError is raised.
popitem()→ (k, v), remove and return some (key, value) pairas 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
update([E ], **F)→ None. Update D from mapping/iterable E and F.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
where(attrs, first=False)Return objects matching child objects properties.
Parameters attrs (dict) – tmux properties to match values of
Returns
Return type list
4.9 API Reference
See also:
Quickstart.
4.9.1 Server Object
class libtmux.Server(socket_name=None, socket_path=None, config_file=None, colors=None,**kwargs)
Bases: libtmux.common.TmuxRelationalObject, libtmux.common.EnvironmentMixin
The tmux(1) server2.
• Server._sessions [Session, . . . ]
– Session._windows [Window , . . . ]2
CLIENTS AND SESSIONS. openbsd manpage for TMUX(1) “The tmux server manages clients, sessions, windows and panes. Clients areattached to sessions to interact with them, either when they are created with the new-session command, or later with the attach-sessioncommand. Each session has one or more windows linked into it. Windows may be linked to multiple sessions and are made up of one ormore panes, each of which contains a pseudo terminal.”
https://man.openbsd.org/tmux.1#CLIENTS_AND_SESSIONS. Accessed April 1st, 2018.
4.9. API Reference 37
libtmux Documentation, Release 0.8.0
* Window._panes [Pane, . . . ]
· Pane
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
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)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()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
_sessionsProperty / alias to return _list_sessions().
list_sessions()Return list of Session from the tmux(1) session.
38 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
Returns
Return type list of Session
sessionsProperty / alias to return list_sessions().
childrenAlias sessions for TmuxRelationalObject
_list_windows()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()Update internal window data and return self for chainability.
Returns
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_cmd which wraps subprocess.Popen.
Returns
Return type list
_update_panes()Update internal pane data and return self for chainability.
Returns
Return type Server
attached_sessionsReturn 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)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. Inter-nally prepends = to the session in $ tmux has-session. tmux 2.1 and up only.
Raises exc.BadSessionName
Returns
4.9. API Reference 39
libtmux Documentation, Release 0.8.0
Return type bool
kill_server()$ tmux kill-server.
find_where(attrs)Return object on first match.
Changed in version 0.4: Renamed from .findWhere to .find_where.
get_by_id(id)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)Kill the tmux session with $ tmux kill-session, return self.
Parameters target_session (str, optional) – target_session: str. note this acceptsfnmatch(3). ‘asdf’ will kill ‘asdfasd’.
Returns
Return type Server
Raises exc.BadSessionName
remove_environment(name)Remove environment variable $ tmux set-environment -r <name>.
Parameters name (str) – the environment variable name. such as ‘PATH’.
set_environment(name, value)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)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 isspecified.
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)Unset environment variable $ tmux set-environment -u <name>.
Parameters name (str) – the environment variable name. such as ‘PATH’.
40 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
where(attrs, first=False)Return objects matching child objects properties.
Parameters attrs (dict) – tmux properties to match values of
Returns
Return type list
switch_client(target_session)$ tmux switch-client.
Parameters target_session (str) – name of the session. fnmatch(3) works.
Raises exc.BadSessionName
attach_session(target_session=None)$ 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, win-dow_name=None, window_command=None, *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 -Adwill 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 isequivalent to:
$ tmux new-session -d
Other Parameters
• kill_session (bool, optional) – Kill current session if $ tmux has-session. Usefulfor testing workspaces.
• start_directory (str, optional) – specifies the working directory in which the new sessionis created.
• window_name (str, optional) –
$ tmux new-session -n <window_name>
• window_command (str) – execute a command on starting the session. The window willclose 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 uponcompletion is desired.
Returns
Return type Session
Raises exc.BadSessionName
4.9. API Reference 41
libtmux Documentation, Release 0.8.0
4.9.2 Session Object
class libtmux.Session(server=None, **kwargs)Bases: libtmux.common.TmuxMappingObject, libtmux.common.TmuxRelationalObject,libtmux.common.EnvironmentMixin
A tmux(1) session3.
Holds Window objects.
Parameters server (Server) –
References
child_id_attribute = u'window_id'unique child ID key for TmuxRelationalObject
formatter_prefix = u'session_'namespace used TmuxMappingObject
cmd(*args, **kwargs)Return server.cmd().
Returns
Return type server.cmd
Notes
Changed in version 0.8: Renamed from .tmux to .cmd.
attach_session()Return $ tmux attach-session aka alias: $ tmux attach.
kill_session()$ tmux kill-session.
switch_client()Switch client to this session.
Raises exc.LibTmuxException
rename_session(new_name)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”, win-dow_shell=None)
Return Window from $ tmux new-window.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.
42 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
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 win-dow 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 isempty string which will create the window in the next available position.
• window_shell (str) – execute a command on starting the window. The window willclose 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)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 itis linked.
Parameters target_window (str, optional) – window to kill
_windowsProperty / alias to return Session._list_windows().
list_windows()Return a list of Window from the tmux(1) session.
Returns
Return type Window
windowsProperty / alias to return Session.list_windows().
childrenAlias windows for TmuxRelationalObject
attached_windowReturn active Window object.
Returns
Return type Window
select_window(target_window)Return Window selected via $ tmux select-window.
Parameters window (str) – target_window also ‘last-window’ (-l), ‘next-window’(-n), or ‘previous-window’ (-p)
Returns
4.9. API Reference 43
libtmux Documentation, Release 0.8.0
Return type Window
Notes
attached_paneReturn active Pane object.
set_option(option, value, _global=False)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 alsoenter ‘on’ or ‘off’ directly.
• _global (bool, optional) – check for option globally across all servers (-g)
Raises
• exc.OptionError, exc.UnknownOption,
• exc.InvalidOption, exc.AmbiguousOption
Notes
show_options(option=None, _global=False)Return a dict of options for the window.
For familiarity with tmux, the option option param forwards to pick a single option, forwarding toSession.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)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
44 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
Raises
• exc.OptionError, exc.UnknownOption,
• exc.InvalidOption, exc.AmbiguousOption
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.
find_where(attrs)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.
get_by_id(id)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
iteritems()→ an iterator over the (key, value) items of D
iterkeys()→ an iterator over the keys of D
itervalues()→ an iterator over the values of D
keys()Return list of keys.
pop(k[, d ])→ v, remove specified key and return the corresponding value.If key is not found, d is returned if given, otherwise KeyError is raised.
popitem()→ (k, v), remove and return some (key, value) pairas a 2-tuple; but raise KeyError if D is empty.
remove_environment(name)Remove environment variable $ tmux set-environment -r <name>.
Parameters name (str) – the environment variable name. such as ‘PATH’.
set_environment(name, value)Set environment $ tmux set-environment <name> <value>.
Parameters
• name (str) – the environment variable name. such as ‘PATH’.
• option (str) – environment value.
4.9. API Reference 45
libtmux Documentation, Release 0.8.0
setdefault(k[, d ])→ D.get(k,d), also set D[k]=d if k not in D
show_environment(name=None)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 isspecified.
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)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.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
where(attrs, first=False)Return objects matching child objects properties.
Parameters attrs (dict) – tmux properties to match values of
Returns
Return type list
4.9.3 Window Object
class libtmux.Window(session=None, **kwargs)Bases: libtmux.common.TmuxMappingObject, libtmux.common.TmuxRelationalObject
A tmux(1) window4.
Holds Pane objects.
Parameters session (Session) –
References
child_id_attribute = u'pane_id'unique child ID key for TmuxRelationalObject
formatter_prefix = u'window_'namespace used TmuxMappingObject
cmd(cmd, *args, **kwargs)Return Server.cmd() defaulting target_window as target.
Send command to tmux with window_id as target-window.4
tmux window. openbsd manpage for TMUX(1). “Each session has one or more windows linked to it. A window occupies the entire screen andmay be split into rectangular panes. . . ”
https://man.openbsd.org/tmux.1#DESCRIPTION. Accessed April 1st, 2018.
46 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
Specifying ('-t', 'custom-target') or ('-tcustom_target') in args will override usingthe 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)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 recenttmux 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 remainingpanes 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 theothers 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)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 acceptsstring of ‘on’ or ‘off’ directly.
Raises
• exc.OptionError, exc.UnknownOption,
• exc.InvalidOption, exc.AmbiguousOption
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 toWindow.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
4.9. API Reference 47
libtmux Documentation, Release 0.8.0
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 (str) –
• g (bool, optional) – Pass -g flag, global. Default False.
Returns
Return type str, int
Raises
• exc.OptionError, exc.UnknownOption,
• exc.InvalidOption, exc.AmbiguousOption
rename_window(new_name)Return Window object $ tmux rename-window <new_name>.
Parameters new_name (str) – name of the window
kill_window()Kill the current Window object. $ tmux kill-window.
move_window(destination=u”, session=None)Move the current Window object $ tmux move-window.
Parameters
• destination (str, optional) – the target window or index to move the win-dow to, default: empty string
• session (str, optional) – the target session or index to move the windowto, default: current session.
select_window()Select window. Return self.
To select a window object asynchrously. If a window object exists and is no longer longer the currentwindow, w.select_window() will make w the current window.
Returns
Return type Window
select_pane(target_pane)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()Return last pane.
split_window(target=None, start_directory=None, attach=True, vertical=True, shell=None)Split window and return the created Pane.
Used for splitting window and holding in a python object.
Parameters
48 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
• attach (bool, optional) – make new window the current window after creating it,default True.
• start_directory (str, optional) – specifies the working directory in whichthe 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 panewill 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 andsplit the pane in another target window, pass in attach=False.
attached_paneReturn the attached Pane.
Returns
Return type Pane
_panesProperty / alias to return _list_panes().
list_panes()Return list of Pane for the window.
Returns
Return type list of Pane
panesProperty / alias to return list_panes().
childrenAlias panes for TmuxRelationalObject
clear()→ None. Remove all items from D.
find_where(attrs)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.
get_by_id(id)Return object based on child_id_attribute.
Parameters val (str) –
4.9. API Reference 49
libtmux Documentation, Release 0.8.0
Returns
Return type object
Notes
Based on .get() from backbone.js.
items()→ list of D’s (key, value) pairs, as 2-tuples
iteritems()→ an iterator over the (key, value) items of D
iterkeys()→ an iterator over the keys of D
itervalues()→ an iterator over the values of D
keys()Return list of keys.
pop(k[, d ])→ v, remove specified key and return the corresponding value.If key is not found, d is returned if given, otherwise KeyError is raised.
popitem()→ (k, v), remove and return some (key, value) pairas 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
update([E ], **F)→ None. Update D from mapping/iterable E and F.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
where(attrs, first=False)Return objects matching child objects properties.
Parameters attrs (dict) – tmux properties to match values of
Returns
Return type list
4.9.4 Pane Object
class libtmux.Pane(window=None, **kwargs)Bases: libtmux.common.TmuxMappingObject, libtmux.common.TmuxRelationalObject
A tmux(1) pane5.
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.
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 certainarea of the display and is a separate terminal.”
https://man.openbsd.org/tmux.1#WINDOWS_AND_PANES. Accessed April 1st, 2018.
50 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
References
formatter_prefix = u'pane_'namespace used TmuxMappingObject
cmd(cmd, *args, **kwargs)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 usingthe object’s pane_id as target.
Returns
Return type Server.cmd
send_keys(cmd, enter=True, suppress_history=True)$ 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.
clear()Clear pane.
reset()Reset and clear pane history.
split_window(attach=False, vertical=True, start_directory=None)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 whichthe new pane is created.
Returns
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) – height of pain, in cells
resize_pane(*args, **kwargs)$ tmux resize-pane of pane and return self.
Parameters target_pane (str) – target_pane, or -U,‘‘-D‘‘, -L, -R.
4.9. API Reference 51
libtmux Documentation, Release 0.8.0
Other Parameters
• height (int) – resize-pane -y dimensions
• width (int) – resize-pane -x dimensions
Returns
Return type Pane
Raises exc.LibTmuxException
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 currentwindow, w.select_pane() will make p the current pane.
Returns
Return type pane
find_where(attrs)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.
get_by_id(id)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
iteritems()→ an iterator over the (key, value) items of D
iterkeys()→ an iterator over the keys of D
itervalues()→ an iterator over the values of D
keys()Return list of keys.
pop(k[, d ])→ v, remove specified key and return the corresponding value.If key is not found, d is returned if given, otherwise KeyError is raised.
popitem()→ (k, v), remove and return some (key, value) pairas 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
52 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
update([E ], **F)→ None. Update D from mapping/iterable E and F.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
where(attrs, first=False)Return objects matching child objects properties.
Parameters attrs (dict) – tmux properties to match values of
Returns
Return type list
4.9.5 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.TmuxRelationalObjectBase Class for managing tmux object child entities. .. # NOQA
Manages collection of child objects (a Server has a collection of Session objects, a Session has collectionof Window)
Children of TmuxRelationalObject are going to have a self.children, self.child_id_attribute.
Object .children methodServer 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 valueServer Server.child_id_attribute session_idSession Session.child_id_attribute window_idWindow Window.child_id_attribute pane_idPane n/a n/a
find_where(attrs)Return object on first match.
Changed in version 0.4: Renamed from .findWhere to .find_where.
get_by_id(id)Return object based on child_id_attribute.
Parameters val (str) –
Returns
Return type object
4.9. API Reference 53
libtmux Documentation, Release 0.8.0
Notes
Based on .get() from backbone.js.
where(attrs, first=False)Return objects matching child objects properties.
Parameters attrs (dict) – tmux properties to match values of
Returns
Return type list
class libtmux.common.TmuxMappingObjectBase: 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. Forexample, a Window will have a window_id and window_name.
Object formatter_prefix valueServer n/a n/aSession Session.formatter_prefix session_Window Window.formatter_prefix window_Pane Pane.formatter_prefix pane_
keys()Return list of keys.
class libtmux.common.EnvironmentMixin(add_option=None)Mixin class for managing session and server level environment variables in tmux.
remove_environment(name)Remove environment variable $ tmux set-environment -r <name>.
Parameters name (str) – the environment variable name. such as ‘PATH’.
set_environment(name, value)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)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 isspecified.
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)Unset environment variable $ tmux set-environment -u <name>.
Parameters name (str) – the environment variable name. such as ‘PATH’.
54 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
class libtmux.common.tmux_cmd(*args, **kwargs)tmux(1) command via subprocess.
Parameters
• tmux_search_paths (list, optional) – Default PATHs to search tmux for, de-faults to default_paths used in which().
• append_env_path (bool) – Append environment PATHs to tmux search paths. Trueby 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’], ap-pend_env_path=True)
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 fromPATH 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()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.
4.9. API Reference 55
libtmux Documentation, Release 0.8.0
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()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()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()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()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()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()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
56 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
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()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 exceptexc.OptionError.
Parameters error (str) – Error response from subprocess call.
Raises
• exc.OptionError, exc.UnknownOption, exc.InvalidOption,
• exc.AmbiguousOption
4.9.6 Exceptions
exception libtmux.exc.LibTmuxExceptionBase Exception for libtmux Errors.
exception libtmux.exc.TmuxCommandNotFoundApplication binary for tmux not found.
exception libtmux.exc.VersionTooLowRaised if tmux below the minimum version to use libtmux.
exception libtmux.exc.TmuxSessionExistsSession does not exist in the server.
exception libtmux.exc.BadSessionNameDisallowed session name for tmux (empty, contains periods or colons).
exception libtmux.exc.OptionErrorRoot error for any error involving invalid, ambiguous or bad options.
exception libtmux.exc.UnknownOptionOption unknown to tmux show-option(s) or show-window-option(s).
exception libtmux.exc.InvalidOptionOption invalid to tmux, introduced in tmux v2.4.
exception libtmux.exc.AmbiguousOptionOption that could potentially match more than one.
4.9. API Reference 57
libtmux Documentation, Release 0.8.0
4.9.7 Test tools
test.retry()Retry a block of code until a time limit or break.
Parameters seconds (int) – Seconds to retry, defaults to RETRY_TIMEOUT_SECONDS, whichis 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_’)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 toTEST_SESSION_PREFIX.
Returns Random session name guaranteed to not collide with current ones.
Return type str
test.get_test_window_name(prefix=u’libtmux_’)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 toTEST_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)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
• args (list) – Arguments passed into Server.new_session()
• kwargs (dict) – Keyword arguments passed into Server.new_session()
58 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
Yields libtmux.Session – Temporary session
Examples
>>> with temp_session(server) as session:... session.new_window(window_name='my window')
test.temp_window(**kwds)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
• args (list) – Arguments passed into Session.new_window()
• kwargs (dict) – Keyword arguments passed into Session.new_window()
Yields libtmux.Window – temporary window
Examples
>>> with temp_window(session) as window:... my_pane = window.split_window()
class libtmux.test.EnvironmentVarGuardMock 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 #1211
References
4.10 Glossary
libtmux Python library for interfacing with tmux through its objects.
tmuxp A tool to manage workspaces with tmux, built on libtmux.
tmux(1) The tmux binary. Used internally to distinguish tmuxp is only a layer on top of tmux.
kaptan configuration management library, see kaptan on github.
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.
4.10. Glossary 59
libtmux Documentation, Release 0.8.0
Server Tmux runs in the background of your system as a process.
The server holds multiple Session. By default, tmux automatically starts the server the first time $ tmux is ran.
A server contains session’s.
tmux starts the server automatically if it’s not running.
Advanced cases: multiple can be run by specifying [-L socket-name] and [-S socket-path].
Client Attaches to a tmux server. When you use tmux through CLI, you are using tmux as a client.
Session Inside a tmux server.
The session has 1 or more Window. The bottom bar in tmux show a list of windows. Normally they can benavigated with Ctrl-a [0-9], Ctrl-a n and Ctrl-a p.
Sessions can have a session_name.
Uniquely identified by session_id.
Window Entity of a session.
Can have 1 or more pane.
Panes can be organized with a layouts.
Windows can have names.
Pane Linked to a Window.
a pseudoterminal.
Target A target, cited in the manual as [-t target] can be a session, window or pane.
4.11 Developing and Testing
Our tests are inside tests/. Tests are implemented using pytest.
make test will create a tmux server on a separate socket_name using $ tmux -L test_case.
4.11.1 Install the latest code from git
To begin developing, check out the code from github:
$ git clone [email protected]:tmux-python/libtmux.git$ cd libtmux
Now create a virtualenv, if you don’t know how to, you can create a virtualenv with:
$ virtualenv .venv
Then activate it to your current tty / terminal session with:
$ source .venv/bin/activate
Good! Now let’s run this:
$ pip install -e .
60 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
This has pip, a python package manager install the python package in the current directory. -emeans --editable,which means you can adjust the code and the installed software will reflect the changes.
$ libtmux
4.11.2 Test Runner
As you seen above, the libtmux command will now be available to you, since you are in the virtual environment,your PATH environment was updated to include a special version of python inside your .venv folder with its ownpackages.
$ make test
You probably didn’t see anything but tests scroll by.
If you found a problem or are trying to write a test, you can file an issue on github.
Test runner options
$ py.test tests/test_common.py
will test the tests/test_common.py tests.
$ py.test tests/test_common.py::test_ignores_letter_versions
tests test_ignore_letter_versions() tests/test_common.py.
Multiple can be separated by spaces:
$ py.test tests/test_{window,pane}.py \tests/test_common.py::test_ignores_letter_versions
Visual testing
You can watch tmux testsuite build sessions visually by keeping a client open in a separate terminal.
Create two terminals:
• Terminal 1: $ tmux -L test_case
• Terminal 2: $ cd into the libtmux project and into the virtualenv if you are using one, see details oninstalling the dev version of libtmux above. Then:
$ py.test tests/test_workspacebuilder.py
Terminal 1 should have flickered and built the session before your eyes. libtmux hides this building from normal users.
4.11.3 Run tests on save
You can re-run tests automatically on file edit.
Note: This requires entr(1).
4.11. Developing and Testing 61
libtmux Documentation, Release 0.8.0
Install entr. Packages are available available on most Linux and BSD variants, including Debian, Ubuntu, FreeBSD,OS X.
To run all tests upon editing any .py file:
$ make watch_test
Rebuild the documentation when an .rst file is edited:
$ cd doc$ make watch
4.11.4 libtmux developer config
After you Install the latest code from git, when inside the libtmux checkout:
$ libtmux load .
this will load the .tmuxp.yaml in the root of the project.
session_name: libtmuxstart_directory: ./ # load session relative to config location (project root).before_script: pipenv install --dev --skip-lockshell_command_before:
- '[ -d `pipenv --venv` ] && source `pipenv --venv`/bin/activate && reset'windows:- window_name: libtmux
focus: Truelayout: main-horizontaloptions:main-pane-height: 35
panes:- focus: true- pane- make watch_test
- window_name: docslayout: main-horizontaloptions:main-pane-height: 35
start_directory: doc/panes:- focus: true- pane- make serve- make watch
Travis CI
libtmux uses travis-ci for continuous integration / automatic unit testing.
libtmux is tested against tmux 1.8 and the latest git source. Interpretters tested are pypy, pypy3, 2.7 and >= 3.3. Thetravis build site uses this .travis.yml configuration:
language: python
(continues on next page)
62 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
(continued from previous page)
sudo: falsepython:
- 2.7- 3.6- pypy3.5-5.10.1- pypy2.7-5.10.0
env:- TMUX_VERSION=master- TMUX_VERSION=2.6- TMUX_VERSION=2.5- TMUX_VERSION=2.4- TMUX_VERSION=2.3- TMUX_VERSION=2.2- TMUX_VERSION=2.1- TMUX_VERSION=2.0- TMUX_VERSION=1.8- TMUX_VERSION=1.9a
matrix:allow_failures:- python: pypy- env: TMUX_VERSION=master
before_install:- export PIP_USE_MIRRORS=true- pip install --upgrade pytest # https://github.com/travis-ci/travis-ci/issues/4873- pip install --upgrade pip wheel virtualenv setuptools- pip install coveralls
install:- pip install -e .
before_script:- git clone https://github.com/tmux/tmux.git tmux- cd tmux- git checkout $TMUX_VERSION- sh autogen.sh- ./configure --prefix=$HOME/tmux && make && make install- export PATH=$PATH:$HOME/tmux/bin- cd ..- tmux -V
script: coverage run --source=libtmux setup.py testaddons:
apt:packages:
- libevent-dev- libncurses-dev
after_success:- bash <(curl -s https://codecov.io/bash)
4.12 History
Here you can find the recent changes to libtmux
• #117: Fix issue with renaming clients with tmux 2.7 on BSD/macOS machines.
• : Move docstrings over to numpy’s style
• : Add sphinxcontrib-napoleon package for documentation
4.12. History 63
libtmux Documentation, Release 0.8.0
• : Sort imports with isort
• #103: Server.new_session learned how to run commands in window on session start, thanks @grimpy!
• #68: Make Server.has_session() use returncode, thanks @jlargentaye! This should make has_session morerobust.
• : Travis/CI: Update pypy veersions
• : Travis/CI: Limit tests to Python 2.7 and 3.6 (removed 3.3 to 3.5)
• : Support package updates to pytest, sphinx, etc.
• : Move to new organization, tmux-python
• #46: Change license from BSD to MIT
• : Port retry function from tmuxp (https://github.com/tmux-python/tmuxp/issues/354)
• : Don’t add -x/-y in tmux >= 2.6 if running tmuxp from inside client.
• : Allow Window.select_layout with no args
• : Fix test where bell- was no longer ambiguous as of tmux 2.6
• : Hotfix to support tmux 2.6 session creation
• #65: Add session id to commands, thanks @askedrelic
• : Exact matches only supported on 2.1 and up
• : Support exact matching in Server.has_session
• #37: Improve support for formatted options like pane-border-status. Thanks @kaushalmodi.
• : Overhaul version checking
– has_version has been renamed to get_version
– get_version will return tmux built from git master as the latest version supported by the libtmuxversion with -master at the end, e.g. 2.4-master
– get_version will return tmux on openbsd base system as the latest version supported by the libtmuxversion with -openbsd at the end, e.g. 2.4-openbsd
– has_required_tmux_version has been renamed to has_minimum_version
– added has_gt_version, has_gte_version, has_lt_version, has_lte_version,
• : Overhaul error handling when setting and showing options
– Added handle_option_error for handling option errors
– Added libtmux.exc.OptionError base exception
– Added libtmux.exc.InvalidOption and libtmux.exc.AmbiguousOption
– libtmux.exc.UnknownOption now extends libtmux.exc.OptionError
• : Add support for tmux 2.4, pypy and pypy3
• : Added TMUX_MIN_VERSION and TMUX_MAX_VERSION
• : Added pydoc exception info to option methods in window and sessions.
• : Fixed up documentation in some session methods
• : Support for python 2.6 dropped. New minimum version is 2.7
• : Add tmux_search_paths and append_env_path kwargs to tmux_cmd.
64 Chapter 4. Donations
libtmux Documentation, Release 0.8.0
• : Add TmuxCommandNotFound exception
• : Fix which command
• #32: support for OpenBSD’s tmux
• #25: support for working with tmux master, thanks @sloria.
• #21: Readme fix from @huwenchao.
• : Pin packages with pyup.io
• #197: use LooseVersion instead of StrictVersion for version checks. Thanks @minijackson.
• : Fix tests and add official support for 2.3
• #19: Add support for start_directory in new sessions and panes, courtesy of @gandelman-a.
• #18: Fix logger, courtesy of @geekli
• : Remove unused target_sesssion param in Server.attach_session and Server.switch_client.
• : Raise exception for invalid session names. tmux does not allow names that are empty, contain periods orcolons.
• #12: - fix logger message when tmux doesn’t exist in PATH
• #8: return None for options that are valid tmux options, but unset at that scope.
• #8: new exception UnknownOption
• #6: major documentation overhaul
• : update which() to find tmux via os.environ['PATH']. https://redd.it/4laeut
• : README and usage fixes
• : .findWhere() is now find_where.
• : _TMUX metadata object changed to _info.
• : attached_sessions, attached_window and attached_pane are now properties.
• : attributes for formatters are now accessible via Session, Window and Pane objects. session.name is equivalent to session.get('session_name'), you can do the same with other properties in_info. window.name, pane.current_path, session.id, window.id, pane.id, session.index, window.index, pane.index, etc.
• switch to pytest
• libtmux forked from tmuxp.
4.12. History 65
libtmux Documentation, Release 0.8.0
66 Chapter 4. Donations
Python Module Index
llibtmux, 30
67
libtmux Documentation, Release 0.8.0
68 Python Module Index
Index
Symbols_list_panes() (libtmux.Server method), 39_list_sessions() (libtmux.Server method), 38_list_windows() (libtmux.Server method), 39_panes (libtmux.Window attribute), 49_sessions (libtmux.Server attribute), 38_update_panes() (libtmux.Server method), 39_update_windows() (libtmux.Server method), 39_windows (libtmux.Session attribute), 43
AAmbiguousOption, 57attach_session() (libtmux.Server method), 41attach_session() (libtmux.Session method), 42attached_pane (libtmux.Session attribute), 44attached_pane (libtmux.Window attribute), 49attached_sessions (libtmux.Server attribute), 39attached_window (libtmux.Session attribute), 43
BBadSessionName, 57
Cchild_id_attribute (libtmux.Server attribute), 38child_id_attribute (libtmux.Session attribute), 42child_id_attribute (libtmux.Window attribute), 46children (libtmux.Server attribute), 39children (libtmux.Session attribute), 43children (libtmux.Window attribute), 49clear() (libtmux.Pane method), 51clear() (libtmux.Session method), 45clear() (libtmux.Window method), 49Client, 60cmd() (libtmux.Pane method), 51cmd() (libtmux.Server method), 38cmd() (libtmux.Session method), 42cmd() (libtmux.Window method), 46colors (libtmux.Server attribute), 38config_file (libtmux.Server attribute), 38
Eenter() (libtmux.Pane method), 52EnvironmentMixin (class in libtmux.common), 54EnvironmentVarGuard (class in libtmux.test), 59
Ffind_where() (libtmux.common.TmuxRelationalObject
method), 53find_where() (libtmux.Pane method), 52find_where() (libtmux.Server method), 40find_where() (libtmux.Session method), 45find_where() (libtmux.Window method), 49formatter_prefix (libtmux.Pane attribute), 51formatter_prefix (libtmux.Server attribute), 38formatter_prefix (libtmux.Session attribute), 42formatter_prefix (libtmux.Window attribute), 46
Gget() (libtmux.Pane method), 52get() (libtmux.Session method), 45get() (libtmux.Window method), 49get_by_id() (libtmux.common.TmuxRelationalObject
method), 53get_by_id() (libtmux.Pane method), 52get_by_id() (libtmux.Server method), 40get_by_id() (libtmux.Session method), 45get_by_id() (libtmux.Window method), 49get_test_session_name() (libtmux.test method), 58get_test_window_name() (libtmux.test method), 58get_version() (libtmux.common method), 55
Hhandle_option_error() (libtmux.common method), 57has_gt_version() (libtmux.common method), 56has_gte_version() (libtmux.common method), 56has_lt_version() (libtmux.common method), 56has_lte_version() (libtmux.common method), 56has_minimum_version() (libtmux.common method), 56has_session() (libtmux.Server method), 39
69
libtmux Documentation, Release 0.8.0
has_version() (libtmux.common method), 56
IInvalidOption, 57items() (libtmux.Pane method), 52items() (libtmux.Session method), 45items() (libtmux.Window method), 50iteritems() (libtmux.Pane method), 52iteritems() (libtmux.Session method), 45iteritems() (libtmux.Window method), 50iterkeys() (libtmux.Pane method), 52iterkeys() (libtmux.Session method), 45iterkeys() (libtmux.Window method), 50itervalues() (libtmux.Pane method), 52itervalues() (libtmux.Session method), 45itervalues() (libtmux.Window method), 50
Kkaptan, 59keys() (libtmux.common.TmuxMappingObject method),
54keys() (libtmux.Pane method), 52keys() (libtmux.Session method), 45keys() (libtmux.Window method), 50kill_server() (libtmux.Server method), 40kill_session() (libtmux.Server method), 40kill_session() (libtmux.Session method), 42kill_window() (libtmux.Session method), 43kill_window() (libtmux.Window method), 48
Llast_pane() (libtmux.Window method), 48libtmux, 59libtmux (module), 12, 15, 21, 30, 35, 37, 60, 63LibTmuxException, 57list_panes() (libtmux.Window method), 49list_sessions() (libtmux.Server method), 38list_windows() (libtmux.Session method), 43
Mmove_window() (libtmux.Window method), 48
Nnew_session() (libtmux.Server method), 41new_window() (libtmux.Session method), 42
OOptionError, 57
PPane, 60Pane (class in libtmux), 50panes (libtmux.Window attribute), 49
pop() (libtmux.Pane method), 52pop() (libtmux.Session method), 45pop() (libtmux.Window method), 50popitem() (libtmux.Pane method), 52popitem() (libtmux.Session method), 45popitem() (libtmux.Window method), 50
Rremove_environment() (libt-
mux.common.EnvironmentMixin method),54
remove_environment() (libtmux.Server method), 40remove_environment() (libtmux.Session method), 45rename_session() (libtmux.Session method), 42rename_window() (libtmux.Window method), 48reset() (libtmux.Pane method), 51resize_pane() (libtmux.Pane method), 51retry() (libtmux.test method), 58
Sselect_layout() (libtmux.Window method), 47select_pane() (libtmux.Pane method), 52select_pane() (libtmux.Window method), 48select_window() (libtmux.Session method), 43select_window() (libtmux.Window method), 48send_keys() (libtmux.Pane method), 51Server, 60Server (class in libtmux), 37Session, 60Session (class in libtmux), 42sessions (libtmux.Server attribute), 39set_environment() (libtmux.common.EnvironmentMixin
method), 54set_environment() (libtmux.Server method), 40set_environment() (libtmux.Session method), 45set_height() (libtmux.Pane method), 51set_option() (libtmux.Session method), 44set_width() (libtmux.Pane method), 51set_window_option() (libtmux.Window method), 47setdefault() (libtmux.Pane method), 52setdefault() (libtmux.Session method), 45setdefault() (libtmux.Window method), 50show_environment() (libt-
mux.common.EnvironmentMixin method),54
show_environment() (libtmux.Server method), 40show_environment() (libtmux.Session method), 46show_option() (libtmux.Session method), 44show_options() (libtmux.Session method), 44show_window_option() (libtmux.Window method), 47show_window_options() (libtmux.Window method), 47socket_name (libtmux.Server attribute), 38socket_path (libtmux.Server attribute), 38split_window() (libtmux.Pane method), 51
70 Index
libtmux Documentation, Release 0.8.0
split_window() (libtmux.Window method), 48switch_client() (libtmux.Server method), 41switch_client() (libtmux.Session method), 42
TTarget, 60temp_session() (libtmux.test method), 58temp_window() (libtmux.test method), 59tmux(1), 59tmux_cmd (class in libtmux.common), 54TMUX_MAX_VERSION (in module libtmux.common),
53TMUX_MIN_VERSION (in module libtmux.common),
53TmuxCommandNotFound, 57TmuxMappingObject (class in libtmux.common), 54tmuxp, 59TmuxRelationalObject (class in libtmux.common), 53TmuxSessionExists, 57
UUnknownOption, 57unset_environment() (libt-
mux.common.EnvironmentMixin method),54
unset_environment() (libtmux.Server method), 40unset_environment() (libtmux.Session method), 46update() (libtmux.Pane method), 52update() (libtmux.Session method), 46update() (libtmux.Window method), 50
Vvalues() (libtmux.Pane method), 53values() (libtmux.Session method), 46values() (libtmux.Window method), 50VersionTooLow, 57
Wwhere() (libtmux.common.TmuxRelationalObject
method), 54where() (libtmux.Pane method), 53where() (libtmux.Server method), 40where() (libtmux.Session method), 46where() (libtmux.Window method), 50which() (libtmux.common method), 55Window, 60Window (class in libtmux), 46windows (libtmux.Session attribute), 43
Index 71