or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

exceptions.mdindex.mdpane.mdserver.mdsession.mdutilities.mdwindow.md

session.mddocs/

0

# Session Management

1

2

Session management in libtmux handles tmux session operations, window collections, environment variables, and session-level configuration. Sessions represent collections of windows and provide isolated environments for terminal workflows.

3

4

## Capabilities

5

6

### Session Initialization and Context

7

8

Create and manage session instances with proper resource management and context support.

9

10

```python { .api }

11

@dataclasses.dataclass()

12

class Session(Obj, EnvironmentMixin):

13

"""

14

tmux Session object.

15

16

Holds Window objects and inherits from Obj and EnvironmentMixin.

17

"""

18

19

server: Server

20

21

def __enter__(self) -> Self:

22

"""Enter the context, returning self."""

23

24

def __exit__(

25

self,

26

exc_type: type[BaseException] | None,

27

exc_value: BaseException | None,

28

exc_tb: types.TracebackType | None

29

) -> None:

30

"""Exit the context, killing the session if it exists."""

31

32

@classmethod

33

def from_session_id(cls, server: Server, session_id: str) -> Session:

34

"""Create Session from existing session_id."""

35

```

36

37

### Session Information and Refresh

38

39

Access and update session state and attributes from tmux.

40

41

```python { .api }

42

def refresh(self) -> None:

43

"""Refresh session attributes from tmux."""

44

45

@property

46

def id(self) -> str | None:

47

"""Alias of Session.session_id."""

48

49

@property

50

def name(self) -> str | None:

51

"""Alias of Session.session_name."""

52

53

@property

54

def active_pane(self) -> Pane | None:

55

"""Return the active Pane object."""

56

57

@property

58

def active_window(self) -> Window:

59

"""Return the active Window object."""

60

```

61

62

### Command Execution

63

64

Execute tmux commands within the session context.

65

66

```python { .api }

67

def cmd(

68

self,

69

cmd: str,

70

*args: t.Any,

71

target: str | int | None = None

72

) -> tmux_cmd:

73

"""

74

Execute tmux subcommand within session context.

75

76

Automatically binds target by adding -t for object's session ID to the command.

77

78

Parameters:

79

- cmd: The tmux command to execute

80

- *args: Additional command arguments

81

- target: Optional custom target override (defaults to session ID)

82

83

Returns:

84

tmux_cmd object with stdout, stderr, and return code

85

"""

86

```

87

88

### Window Operations

89

90

Create, manage, and query windows within the session.

91

92

```python { .api }

93

def new_window(

94

self,

95

window_name: str | None = None,

96

*,

97

start_directory: StrPath | None = None,

98

attach: bool = False,

99

window_index: str = "",

100

window_shell: str | None = None,

101

environment: dict[str, str] | None = None,

102

direction: WindowDirection | None = None,

103

target_window: str | None = None

104

) -> Window:

105

"""

106

Create new window, returns new Window.

107

108

By default, this will make the window active. For the new window

109

to be created and not set to current, pass in attach=False.

110

111

Parameters:

112

- window_name: Name for the new window

113

- start_directory: Working directory in which the new window is created

114

- attach: Make new window the current window after creating it (default False)

115

- window_index: Create window at given index position (empty string for next available)

116

- window_shell: Execute command on starting the window

117

- environment: Environment variables for window (tmux 3.0+)

118

- direction: Insert window before or after target window (tmux 3.2+)

119

- target_window: Used by Window.new_window to specify target window

120

121

Returns:

122

Window object for the created window

123

"""

124

125

def select_window(self, target_window: str | int) -> Window:

126

"""

127

Select window and return the selected window.

128

129

Parameters:

130

- target_window: Window name/index, or 'last-window', 'next-window', 'previous-window'

131

132

Returns:

133

Selected Window object

134

"""

135

136

def kill_window(self, target_window: str | None = None) -> None:

137

"""

138

Close a tmux window, and all panes inside it.

139

140

Kill the current window or the window at target-window, removing it

141

from any sessions to which it is linked.

142

143

Parameters:

144

- target_window: Window to kill (optional)

145

"""

146

```

147

148

### Session Lifecycle

149

150

Control session attachment, detachment, renaming, and termination.

151

152

```python { .api }

153

def attach(

154

self,

155

exit_: bool | None = None,

156

flags_: list[str] | None = None

157

) -> Session:

158

"""

159

Return tmux attach-session (alias: tmux attach).

160

161

Parameters:

162

- exit_: Exit the client after attaching session

163

- flags_: Additional flags to pass to attach-session

164

165

Returns:

166

Session instance for method chaining

167

"""

168

169

def kill(

170

self,

171

all_except: bool | None = None,

172

clear: bool | None = None

173

) -> None:

174

"""

175

Kill Session, closes linked windows and detach all clients.

176

177

Parameters:

178

- all_except: Kill all sessions in server except this one

179

- clear: Clear alerts (bell, activity, or silence) in all windows

180

"""

181

182

def rename_session(self, new_name: str) -> Session:

183

"""

184

Rename session and return new Session object.

185

186

Parameters:

187

- new_name: New session name

188

189

Returns:

190

Session instance for method chaining

191

192

Raises:

193

BadSessionName: If session name is invalid

194

"""

195

196

def switch_client(self) -> Session:

197

"""

198

Switch client to session.

199

200

Returns:

201

Session instance for method chaining

202

203

Raises:

204

LibTmuxException: If tmux command fails

205

"""

206

```

207

208

### Session Options

209

210

Configure session-level tmux options and settings.

211

212

```python { .api }

213

def set_option(

214

self,

215

option: str,

216

value: str | int,

217

global_: bool = False

218

) -> Session:

219

"""

220

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

221

222

Parameters:

223

- option: The session option (e.g., 'default-shell')

224

- value: Option value (True/False becomes 'on'/'off')

225

- global_: Check for option globally across all servers (-g)

226

227

Returns:

228

Session instance for method chaining

229

230

Raises:

231

OptionError, UnknownOption, InvalidOption, AmbiguousOption

232

"""

233

234

def show_options(

235

self,

236

global_: bool | None = False

237

) -> dict[str, str | int]:

238

"""

239

Return dict of options for the session.

240

241

Parameters:

242

- global_: Pass -g flag for global variable (server-wide)

243

244

Returns:

245

Dictionary of option names and values

246

"""

247

248

def show_option(

249

self,

250

option: str,

251

global_: bool = False

252

) -> str | int | bool | None:

253

"""

254

Return option value for the target session.

255

256

Parameters:

257

- option: Option name

258

- global_: Use global option scope, same as -g

259

260

Returns:

261

Option value (str, int, bool, or None if not found)

262

263

Raises:

264

OptionError, UnknownOption, InvalidOption, AmbiguousOption

265

"""

266

```

267

268

### Environment Variable Management

269

270

Manage session-level environment variables through inherited EnvironmentMixin.

271

272

```python { .api }

273

# Inherited from EnvironmentMixin

274

def set_environment(self, name: str, value: str) -> Session:

275

"""Set environment variable for session."""

276

277

def unset_environment(self, name: str) -> Session:

278

"""Unset environment variable for session."""

279

280

def remove_environment(self, name: str) -> Session:

281

"""Remove environment variable from session."""

282

283

def show_environment(self, global_: bool = False) -> dict[str, str]:

284

"""Get all environment variables as dictionary."""

285

286

def getenv(self, name: str) -> str | None:

287

"""Get specific environment variable value."""

288

```

289

290

### Collection Properties

291

292

Access collections of windows and panes within the session.

293

294

```python { .api }

295

@property

296

def windows(self) -> QueryList[Window]:

297

"""QueryList of windows in session."""

298

299

@property

300

def panes(self) -> QueryList[Pane]:

301

"""QueryList of all panes across session's windows."""

302

```

303

304

## Usage Examples

305

306

### Basic Session Operations

307

308

```python

309

import libtmux

310

311

server = libtmux.Server()

312

session = server.new_session('my_session')

313

314

# Get session information

315

print(f"Session ID: {session.id}")

316

print(f"Session Name: {session.name}")

317

318

# Refresh session state

319

session.refresh()

320

```

321

322

### Context Manager Usage

323

324

```python

325

import libtmux

326

327

server = libtmux.Server()

328

with server.new_session('temp_session') as session:

329

# Work with session

330

window = session.new_window('work')

331

# Session automatically cleaned up on exit

332

```

333

334

### Window Management

335

336

```python

337

import libtmux

338

339

server = libtmux.Server()

340

session = server.new_session('dev')

341

342

# Create windows

343

editor = session.new_window('editor', window_command='vim')

344

terminal = session.new_window('terminal')

345

logs = session.new_window('logs', start_directory='/var/log')

346

347

# Query windows

348

for window in session.windows:

349

print(f"Window: {window.name}")

350

351

# Find specific windows

352

vim_windows = session.find_where(window_name='editor')

353

```

354

355

### Environment Management

356

357

```python

358

import libtmux

359

360

server = libtmux.Server()

361

session = server.new_session('env_test')

362

363

# Set environment variables

364

session.set_environment('PROJECT_ROOT', '/home/user/project')

365

session.set_environment('DEBUG', '1')

366

367

# Get environment variables

368

project_root = session.getenv('PROJECT_ROOT')

369

all_env = session.show_environment()

370

371

# Clean up environment

372

session.unset_environment('DEBUG')

373

```

374

375

### Session Options

376

377

```python

378

import libtmux

379

380

server = libtmux.Server()

381

session = server.new_session('configured')

382

383

# Set session options

384

session.set_option('mouse', 'on')

385

session.set_option('base-index', '1')

386

387

# Get options

388

mouse_setting = session.show_option('mouse')

389

all_options = session.show_options()

390

```