0
# Server Management
1
2
Server management in libtmux handles tmux server connections, lifecycle operations, and global server-level functionality. The Server class provides methods to connect to tmux servers, manage sessions across the server, and execute server-wide commands.
3
4
## Capabilities
5
6
### Server Connection and Initialization
7
8
Create and configure connections to tmux servers with support for custom socket paths, configuration files, and color settings.
9
10
```python { .api }
11
class Server:
12
def __init__(
13
self,
14
socket_name: str | None = None,
15
socket_path: str | pathlib.Path | None = None,
16
config_file: str | None = None,
17
colors: int | None = None,
18
on_init: t.Callable[[Server], None] | None = None,
19
socket_name_factory: t.Callable[[], str] | None = None,
20
**kwargs: t.Any
21
) -> None:
22
"""
23
Initialize tmux server connection.
24
25
Parameters:
26
- socket_name: Named socket identifier for tmux server
27
- socket_path: Full path to tmux socket file or Path object
28
- config_file: Path to tmux configuration file
29
- colors: Color support (256 or 88)
30
- on_init: Callback function called after initialization
31
- socket_name_factory: Factory function to generate socket name
32
- **kwargs: Additional keyword arguments
33
"""
34
35
def __enter__(self) -> Self:
36
"""Enter the context, returning self."""
37
38
def __exit__(
39
self,
40
exc_type: type[BaseException] | None,
41
exc_value: BaseException | None,
42
exc_tb: types.TracebackType | None
43
) -> None:
44
"""Exit the context, killing the server if it exists."""
45
```
46
47
### Server Status and Health
48
49
Check server connection status and ensure server availability for operations.
50
51
```python { .api }
52
def is_alive(self) -> bool:
53
"""Check if tmux server is running and accessible."""
54
55
def raise_if_dead(self):
56
"""Raise TmuxCommandNotFound if server is not running."""
57
```
58
59
### Command Execution
60
61
Execute tmux commands within the server context with proper error handling and output capture.
62
63
```python { .api }
64
def cmd(
65
self,
66
cmd: str,
67
*args: t.Any,
68
target: str | int | None = None
69
) -> tmux_cmd:
70
"""
71
Execute tmux command on server.
72
73
Parameters:
74
- cmd: The tmux command to execute
75
- *args: Additional command arguments
76
- target: Optional target for the command
77
78
Returns:
79
tmux_cmd object with stdout, stderr, and return code
80
"""
81
```
82
83
### Session Operations
84
85
Create, manage, and query sessions on the tmux server.
86
87
```python { .api }
88
def new_session(
89
self,
90
session_name: str | None = None,
91
kill_session: bool = False,
92
attach: bool = False,
93
start_directory: StrPath | None = None,
94
window_name: str | None = None,
95
window_command: str | None = None,
96
x: int | DashLiteral | None = None,
97
y: int | DashLiteral | None = None,
98
environment: dict[str, str] | None = None,
99
*args: t.Any,
100
**kwargs: t.Any
101
) -> Session:
102
"""
103
Create new tmux session.
104
105
Parameters:
106
- session_name: Name for the new session
107
- kill_session: Kill existing session if it exists
108
- attach: Whether to attach to session after creation
109
- start_directory: Starting directory for session (str or PathLike)
110
- window_name: Name for initial window
111
- window_command: Command to run in initial window
112
- x: Force specified width for detached session
113
- y: Force specified height for detached session
114
- environment: Environment variables to set (tmux 3.2+)
115
- *args: Additional positional arguments
116
- **kwargs: Additional keyword arguments
117
118
Returns:
119
Session object for the created session
120
121
Raises:
122
TmuxSessionExists: If session name already exists and kill_session=False
123
BadSessionName: If session name is invalid
124
"""
125
126
def has_session(self, target_session: str, exact: bool = True) -> bool:
127
"""
128
Check if session exists by name or ID.
129
130
Parameters:
131
- target_session: Session name to check
132
- exact: Match session name exactly (tmux 2.1+)
133
134
Returns:
135
True if session exists, False otherwise
136
137
Raises:
138
BadSessionName: If session name is invalid
139
"""
140
141
def kill_session(self, target_session: str | int) -> Server:
142
"""
143
Kill session by name or ID.
144
145
Parameters:
146
- target_session: Session name or ID to kill
147
148
Returns:
149
Server instance for method chaining
150
151
Raises:
152
BadSessionName: If session name is invalid
153
LibTmuxException: If tmux command fails
154
"""
155
156
def attach_session(self, target_session: str | None = None) -> None:
157
"""
158
Attach to existing session.
159
160
Parameters:
161
- target_session: Session name to attach to
162
163
Raises:
164
BadSessionName: If session name is invalid
165
LibTmuxException: If tmux command fails
166
"""
167
168
def switch_client(self, target_session: str) -> None:
169
"""
170
Switch client to different session.
171
172
Parameters:
173
- target_session: Session name to switch to
174
175
Raises:
176
BadSessionName: If session name is invalid
177
LibTmuxException: If tmux command fails
178
"""
179
```
180
181
### Server Termination
182
183
Terminate the entire tmux server and all associated sessions.
184
185
```python { .api }
186
def kill(self):
187
"""Kill tmux server and all sessions."""
188
```
189
190
### Collection Properties
191
192
Access collections of tmux objects across the entire server.
193
194
```python { .api }
195
@property
196
def sessions(self) -> QueryList[Session]:
197
"""QueryList of all sessions on server."""
198
199
@property
200
def windows(self) -> QueryList[Window]:
201
"""QueryList of all windows across all sessions."""
202
203
@property
204
def panes(self) -> QueryList[Pane]:
205
"""QueryList of all panes across all sessions."""
206
207
@property
208
def attached_sessions(self) -> List[Session]:
209
"""List of currently attached sessions."""
210
```
211
212
### Server Attributes
213
214
Access server configuration and connection details.
215
216
```python { .api }
217
socket_name: str | None
218
"""Socket name for tmux server connection. Passthrough to [-L socket-name]."""
219
220
socket_path: str | pathlib.Path | None
221
"""Full socket path for tmux server connection. Passthrough to [-S socket-path]."""
222
223
config_file: str | None
224
"""Path to tmux configuration file. Passthrough to [-f file]."""
225
226
colors: int | None
227
"""Color support level (256 or 88)."""
228
229
child_id_attribute: str
230
"""Unique child ID used by TmuxRelationalObject."""
231
232
formatter_prefix: str
233
"""Namespace used for TmuxMappingObject."""
234
```
235
236
## Usage Examples
237
238
### Basic Server Connection
239
240
```python
241
import libtmux
242
243
# Connect to default tmux server
244
server = libtmux.Server()
245
246
# Connect to named socket
247
server = libtmux.Server(socket_name='my_socket')
248
249
# Connect with custom configuration
250
server = libtmux.Server(
251
socket_name='dev_socket',
252
config_file='~/.tmux-dev.conf',
253
colors=256
254
)
255
```
256
257
### Context Manager Usage
258
259
```python
260
import libtmux
261
262
with libtmux.Server() as server:
263
session = server.new_session('work')
264
# Server automatically cleaned up on exit
265
```
266
267
### Session Management
268
269
```python
270
import libtmux
271
272
server = libtmux.Server()
273
274
# Create new session
275
session = server.new_session(
276
session_name='development',
277
window_name='editor',
278
start_directory='/home/user/projects'
279
)
280
281
# Check if session exists
282
if server.has_session('development'):
283
print("Session exists")
284
285
# List all sessions
286
for session in server.sessions:
287
print(f"Session: {session.name}")
288
289
# Kill specific session
290
server.kill_session('development')
291
```