| 1 | (automation-patterns)= |
| 2 | |
| 3 | # Automation patterns |
| 4 | |
| 5 | When you automate a terminal workflow, you are usually coordinating more than one |
| 6 | process: you kick off work in one pane, watch another for a completion signal, and |
| 7 | keep several tasks moving without blocking on any single one. libtmux's object API |
| 8 | makes that coordination ordinary Python — you start commands with |
| 9 | {meth}`~libtmux.Pane.send_keys`, read what came back with |
| 10 | {meth}`~libtmux.Pane.capture_pane`, and fan work across panes with |
| 11 | {meth}`~libtmux.Pane.split`. This guide collects the patterns that turn a loose |
| 12 | pile of {meth}`send_keys() <libtmux.Pane.send_keys>` calls into automation you |
| 13 | can trust: output monitoring, timeouts, retries, and multi-pane orchestration. |
| 14 | |
| 15 | Most scripts only need a couple of these patterns. Output monitoring and the |
| 16 | context manager patterns cover the common case — send a command, wait for a |
| 17 | marker, clean up after yourself — so start there. The later sections (state |
| 18 | machines, task queues) are for the rarer cases where a single pane drives a longer |
| 19 | sequence of steps; reach for them when you actually need them. |
| 20 | |
| 21 | These patterns lean on polling: you call {meth}`~libtmux.Pane.capture_pane` in a |
| 22 | loop and `sleep` between reads. That is simpler than wiring up an event-driven |
| 23 | system, and it costs you latency — each poll is a tmux round-trip, and a `sleep` |
| 24 | between polls is dead time you pay whether the command finished or not. For most |
| 25 | automation that trade is worth it. When milliseconds matter, look instead at tmux |
| 26 | hooks or an external event-driven framework. |
| 27 | |
| 28 | Open two terminals: |
| 29 | |
| 30 | Terminal one: start tmux: |
| 31 | |
| 32 | ```console |
| 33 | $ tmux |
| 34 | ``` |
| 35 | |
| 36 | Terminal two, `python` or `ptpython` if you have it: |
| 37 | |
| 38 | ```console |
| 39 | $ python |
| 40 | ``` |
| 41 | |
| 42 | The examples below assume you already have `server` and `session` objects in scope. |
| 43 | In this documentation they come from libtmux's |
| 44 | {doc}`pytest fixtures </api/testing/pytest-plugin/fixtures>`, which run the |
| 45 | doctests against a live tmux server; in your own scripts you create them yourself |
| 46 | (a {class}`~libtmux.Server` and a session from |
| 47 | {meth}`~libtmux.Server.new_session`). Each example builds its own window or pane and |
| 48 | tears it down at the end, so the snippets stand alone and don't depend on each other. |
| 49 | |
| 50 | ## Process control |
| 51 | |
| 52 | ### Starting long-running processes |
| 53 | |
| 54 | When you send a command to a pane with {meth}`~libtmux.Pane.send_keys`, it runs in |
| 55 | the background — control returns to your script immediately, while the command keeps |
| 56 | going in the pane. The pane object stays your handle on that running work. |
| 57 | |
| 58 | ```python |
| 59 | >>> import time |
| 60 | |
| 61 | >>> proc_window = session.new_window(window_name='process', attach=False) |
| 62 | >>> proc_pane = proc_window.active_pane |
| 63 | |
| 64 | >>> # Start a background process |
| 65 | >>> proc_pane.send_keys('sleep 2 && echo "Process complete"') |
| 66 | |
| 67 | >>> # Process is running |
| 68 | >>> time.sleep(0.1) |
| 69 | >>> proc_window.window_name |
| 70 | 'process' |
| 71 | |
| 72 | >>> # Clean up |
| 73 | >>> proc_window.kill() |
| 74 | ``` |
| 75 | |
| 76 | ### Checking process status |
| 77 | |
| 78 | Because {meth}`send_keys() <libtmux.Pane.send_keys>` doesn't wait, you find out |
| 79 | whether a command is still running the same way a person would: by reading |
| 80 | what's on screen. Capture the pane and look for a marker your command prints |
| 81 | when it reaches a known state. |
| 82 | |
| 83 | ```python |
| 84 | >>> import time |
| 85 | |
| 86 | >>> status_window = session.new_window(window_name='status-check', attach=False) |
| 87 | >>> status_pane = status_window.active_pane |
| 88 | |
| 89 | >>> def is_process_running(pane, marker='RUNNING'): |
| 90 | ... """Check if a marker indicates process is still running.""" |
| 91 | ... output = pane.capture_pane() |
| 92 | ... return marker in '\\n'.join(output) |
| 93 | |
| 94 | >>> # Start and mark a process |
| 95 | >>> status_pane.send_keys('echo "RUNNING"; sleep 0.3; echo "DONE"') |
| 96 | >>> time.sleep(0.1) |
| 97 | |
| 98 | >>> # Check while running |
| 99 | >>> 'RUNNING' in '\\n'.join(status_pane.capture_pane()) |
| 100 | True |
| 101 | |
| 102 | >>> # Wait for completion |
| 103 | >>> time.sleep(0.5) |
| 104 | >>> 'DONE' in '\\n'.join(status_pane.capture_pane()) |
| 105 | True |
| 106 | |
| 107 | >>> # Clean up |
| 108 | >>> status_window.kill() |
| 109 | ``` |
| 110 | |
| 111 | ## Output monitoring |
| 112 | |
| 113 | ### Waiting for specific output |
| 114 | |
| 115 | The workhorse of terminal automation is "run something, then block until a string |
| 116 | shows up." You wrap {meth}`~libtmux.Pane.capture_pane` in a loop with a timeout, so a |
| 117 | command that never finishes can't hang your script forever. The `poll_interval` is |
| 118 | the latency/work trade in one knob: poll faster to react sooner, slower to spare tmux |
| 119 | the round-trips. |
| 120 | |
| 121 | ```python |
| 122 | >>> import time |
| 123 | |
| 124 | >>> monitor_window = session.new_window(window_name='monitor', attach=False) |
| 125 | >>> monitor_pane = monitor_window.active_pane |
| 126 | |
| 127 | >>> def wait_for_output(pane, text, timeout=5.0, poll_interval=0.1): |
| 128 | ... """Wait for specific text to appear in pane output.""" |
| 129 | ... start = time.time() |
| 130 | ... while time.time() - start < timeout: |
| 131 | ... output = '\\n'.join(pane.capture_pane()) |
| 132 | ... if text in output: |
| 133 | ... return True |
| 134 | ... time.sleep(poll_interval) |
| 135 | ... return False |
| 136 | |
| 137 | >>> monitor_pane.send_keys('sleep 0.2; echo "READY"') |
| 138 | >>> wait_for_output(monitor_pane, 'READY', timeout=2.0) |
| 139 | True |
| 140 | |
| 141 | >>> # Clean up |
| 142 | >>> monitor_window.kill() |
| 143 | ``` |
| 144 | |
| 145 | ### Detecting errors in output |
| 146 | |
| 147 | Waiting for success is only half the job — you also want to notice failure. The same |
| 148 | capture-and-scan approach works for spotting error patterns, so you can bail out |
| 149 | early instead of timing out on a command that already crashed. |
| 150 | |
| 151 | ```python |
| 152 | >>> import time |
| 153 | |
| 154 | >>> error_window = session.new_window(window_name='error-check', attach=False) |
| 155 | >>> error_pane = error_window.active_pane |
| 156 | |
| 157 | >>> def check_for_errors(pane, patterns=None): |
| 158 | ... """Check pane output for error patterns.""" |
| 159 | ... if patterns is None: |
| 160 | ... patterns = ['Error:', 'error:', 'ERROR', 'FAILED', 'Exception'] |
| 161 | ... output = '\\n'.join(pane.capture_pane()) |
| 162 | ... for pattern in patterns: |
| 163 | ... if pattern in output: |
| 164 | ... return pattern |
| 165 | ... return None |
| 166 | |
| 167 | >>> # Test with successful output |
| 168 | >>> error_pane.send_keys('echo "Success!"') |
| 169 | >>> time.sleep(0.1) |
| 170 | >>> check_for_errors(error_pane) is None |
| 171 | True |
| 172 | |
| 173 | >>> # Clean up |
| 174 | >>> error_window.kill() |
| 175 | ``` |
| 176 | |
| 177 | ### Capturing output between markers |
| 178 | |
| 179 | Sometimes you don't want the whole scrollback — you want just the lines a command |
| 180 | produced. Bracket the interesting output with a marker you control, then return |
| 181 | everything that follows it. This is how you pull a command's result out of a shared |
| 182 | pane without dragging along the prompt and prior history. |
| 183 | |
| 184 | ```python |
| 185 | >>> import time |
| 186 | |
| 187 | >>> capture_window = session.new_window(window_name='capture', attach=False) |
| 188 | >>> capture_pane = capture_window.active_pane |
| 189 | |
| 190 | >>> def capture_after_marker(pane, marker, timeout=5.0): |
| 191 | ... """Capture output after a marker appears.""" |
| 192 | ... start_time = time.time() |
| 193 | ... while time.time() - start_time < timeout: |
| 194 | ... lines = pane.capture_pane() |
| 195 | ... output = '\\n'.join(lines) |
| 196 | ... if marker in output: |
| 197 | ... # Return all lines after the marker |
| 198 | ... found = False |
| 199 | ... result = [] |
| 200 | ... for line in lines: |
| 201 | ... if marker in line: |
| 202 | ... found = True |
| 203 | ... continue |
| 204 | ... if found: |
| 205 | ... result.append(line) |
| 206 | ... return result |
| 207 | ... time.sleep(0.1) |
| 208 | ... return None |
| 209 | |
| 210 | >>> # Test marker capture |
| 211 | >>> capture_pane.send_keys('echo "MARKER"; echo "captured data"') |
| 212 | >>> time.sleep(0.3) |
| 213 | >>> result = capture_after_marker(capture_pane, 'MARKER', timeout=2.0) |
| 214 | >>> any('captured' in line for line in (result or [])) |
| 215 | True |
| 216 | |
| 217 | >>> # Clean up |
| 218 | >>> capture_window.kill() |
| 219 | ``` |
| 220 | |
| 221 | ## Multi-pane orchestration |
| 222 | |
| 223 | ### Running parallel tasks |
| 224 | |
| 225 | To run work in parallel, give each task its own pane. You split the window with |
| 226 | {meth}`~libtmux.Pane.split`, choosing where the new pane lands with |
| 227 | {class}`~libtmux.constants.PaneDirection`, then fire a command into each. Because |
| 228 | {meth}`send_keys() <libtmux.Pane.send_keys>` returns immediately, the tasks run |
| 229 | concurrently; you gather their results afterward by capturing every pane. |
| 230 | |
| 231 | ```python |
| 232 | >>> import time |
| 233 | >>> from libtmux.constants import PaneDirection |
| 234 | |
| 235 | >>> parallel_window = session.new_window(window_name='parallel', attach=False) |
| 236 | >>> parallel_window.resize(height=40, width=120) # doctest: +ELLIPSIS |
| 237 | Window(@... ...) |
| 238 | |
| 239 | >>> pane1 = parallel_window.active_pane |
| 240 | >>> pane2 = pane1.split(direction=PaneDirection.Right) |
| 241 | >>> pane3 = pane1.split(direction=PaneDirection.Below) |
| 242 | |
| 243 | >>> # Start tasks in parallel |
| 244 | >>> tasks = [ |
| 245 | ... (pane1, 'echo "Task 1"; sleep 0.2; echo "DONE1"'), |
| 246 | ... (pane2, 'echo "Task 2"; sleep 0.1; echo "DONE2"'), |
| 247 | ... (pane3, 'echo "Task 3"; sleep 0.3; echo "DONE3"'), |
| 248 | ... ] |
| 249 | |
| 250 | >>> for pane, cmd in tasks: |
| 251 | ... pane.send_keys(cmd) |
| 252 | |
| 253 | >>> # Wait for all tasks |
| 254 | >>> time.sleep(0.5) |
| 255 | |
| 256 | >>> # Verify all completed |
| 257 | >>> all('DONE' in '\\n'.join(p.capture_pane()) for p, _ in tasks) |
| 258 | True |
| 259 | |
| 260 | >>> # Clean up |
| 261 | >>> parallel_window.kill() |
| 262 | ``` |
| 263 | |
| 264 | ### Monitoring multiple panes for completion |
| 265 | |
| 266 | A fixed `sleep` only works when you know how long the slowest task takes. When tasks |
| 267 | finish at different times, watch them all at once and drop each pane from the |
| 268 | watch-list as its marker appears — you return as soon as the last one completes, |
| 269 | instead of always waiting for a worst-case timeout. |
| 270 | |
| 271 | ```python |
| 272 | >>> import time |
| 273 | >>> from libtmux.constants import PaneDirection |
| 274 | |
| 275 | >>> multi_window = session.new_window(window_name='multi-monitor', attach=False) |
| 276 | >>> multi_window.resize(height=40, width=120) # doctest: +ELLIPSIS |
| 277 | Window(@... ...) |
| 278 | |
| 279 | >>> panes = [multi_window.active_pane] |
| 280 | >>> panes.append(panes[0].split(direction=PaneDirection.Right)) |
| 281 | >>> panes.append(panes[0].split(direction=PaneDirection.Below)) |
| 282 | |
| 283 | >>> def wait_all_complete(panes, marker='COMPLETE', timeout=10.0): |
| 284 | ... """Wait for all panes to show completion marker.""" |
| 285 | ... start = time.time() |
| 286 | ... remaining = set(range(len(panes))) |
| 287 | ... while remaining and time.time() - start < timeout: |
| 288 | ... for i in list(remaining): |
| 289 | ... if marker in '\\n'.join(panes[i].capture_pane()): |
| 290 | ... remaining.remove(i) |
| 291 | ... time.sleep(0.1) |
| 292 | ... return len(remaining) == 0 |
| 293 | |
| 294 | >>> # Start tasks with different durations |
| 295 | >>> for i, pane in enumerate(panes): |
| 296 | ... pane.send_keys(f'sleep 0.{i+1}; echo "COMPLETE"') |
| 297 | |
| 298 | >>> # Wait for all |
| 299 | >>> wait_all_complete(panes, 'COMPLETE', timeout=2.0) |
| 300 | True |
| 301 | |
| 302 | >>> # Clean up |
| 303 | >>> multi_window.kill() |
| 304 | ``` |
| 305 | |
| 306 | ## Context manager patterns |
| 307 | |
| 308 | ### Temporary session for isolated work |
| 309 | |
| 310 | Cleanup is the part of automation that's easy to forget — and forgetting leaves |
| 311 | orphaned sessions and windows behind on the tmux server. A `with` block makes the |
| 312 | cleanup automatic: the session lives for the body and is killed on the way out, even |
| 313 | if an exception interrupts you. It costs a little to spin a session up and tear it |
| 314 | down, but you get a guaranteed-clean slate that never leaks. |
| 315 | |
| 316 | ```python |
| 317 | >>> # Create isolated session for a task |
| 318 | >>> with server.new_session(session_name='temp-work') as temp_session: |
| 319 | ... window = temp_session.new_window(window_name='task') |
| 320 | ... pane = window.active_pane |
| 321 | ... pane.send_keys('echo "Isolated work"') |
| 322 | ... # Session exists during work |
| 323 | ... temp_session in server.sessions |
| 324 | True |
| 325 | |
| 326 | >>> # Session automatically killed after context |
| 327 | >>> temp_session not in server.sessions |
| 328 | True |
| 329 | ``` |
| 330 | |
| 331 | ### Temporary window for subtask |
| 332 | |
| 333 | When you only need a scratch space for one subtask, scope a window the same way. The |
| 334 | window opens for the body of the block and is gone afterward, so a short-lived job |
| 335 | never outlives its purpose. |
| 336 | |
| 337 | ```python |
| 338 | >>> import time |
| 339 | |
| 340 | >>> with session.new_window(window_name='subtask') as sub_window: |
| 341 | ... pane = sub_window.active_pane |
| 342 | ... pane.send_keys('echo "Subtask running"') |
| 343 | ... time.sleep(0.1) |
| 344 | ... 'Subtask' in '\\n'.join(pane.capture_pane()) |
| 345 | True |
| 346 | |
| 347 | >>> # Window cleaned up automatically |
| 348 | >>> sub_window not in session.windows |
| 349 | True |
| 350 | ``` |
| 351 | |
| 352 | ## Timeout handling |
| 353 | |
| 354 | ### Command with timeout |
| 355 | |
| 356 | Any command you wait on can hang, so give every wait an upper bound. Pair the command |
| 357 | with a completion marker and poll until either the marker shows up or the clock runs |
| 358 | out — and when it runs out, raise, so a stuck command surfaces as an error you can |
| 359 | catch instead of a script that quietly stalls. |
| 360 | |
| 361 | ```python |
| 362 | >>> import time |
| 363 | |
| 364 | >>> timeout_window = session.new_window(window_name='timeout-demo', attach=False) |
| 365 | >>> timeout_pane = timeout_window.active_pane |
| 366 | |
| 367 | >>> class CommandTimeout(Exception): |
| 368 | ... """Raised when a command times out.""" |
| 369 | ... pass |
| 370 | |
| 371 | >>> def run_with_timeout(pane, command, marker='__DONE__', timeout=5.0): |
| 372 | ... """Run command and wait for completion with timeout.""" |
| 373 | ... pane.send_keys(f'{command}; echo {marker}') |
| 374 | ... start = time.time() |
| 375 | ... while time.time() - start < timeout: |
| 376 | ... output = '\\n'.join(pane.capture_pane()) |
| 377 | ... if marker in output: |
| 378 | ... return output |
| 379 | ... time.sleep(0.1) |
| 380 | ... raise CommandTimeout(f'Command timed out after {timeout}s') |
| 381 | |
| 382 | >>> # Test successful command |
| 383 | >>> result = run_with_timeout(timeout_pane, 'echo "fast"', timeout=2.0) |
| 384 | >>> 'fast' in result |
| 385 | True |
| 386 | |
| 387 | >>> # Clean up |
| 388 | >>> timeout_window.kill() |
| 389 | ``` |
| 390 | |
| 391 | ### Retry pattern |
| 392 | |
| 393 | For flaky work that succeeds on a later attempt, retry until a success marker |
| 394 | appears. Be honest about the cost: each retry runs the command again and waits the |
| 395 | full `delay`, so a slow `delay` times `max_retries` is the worst case you're signing |
| 396 | up for. Tune both for how expensive the command is and how patient you can be. |
| 397 | |
| 398 | ```python |
| 399 | >>> import time |
| 400 | |
| 401 | >>> retry_window = session.new_window(window_name='retry-demo', attach=False) |
| 402 | >>> retry_pane = retry_window.active_pane |
| 403 | |
| 404 | >>> def retry_until_success(pane, command, success_marker, max_retries=3, delay=0.5): |
| 405 | ... """Retry command until success marker appears.""" |
| 406 | ... for attempt in range(max_retries): |
| 407 | ... pane.send_keys(command) |
| 408 | ... time.sleep(delay) |
| 409 | ... output = '\\n'.join(pane.capture_pane()) |
| 410 | ... if success_marker in output: |
| 411 | ... return True, attempt + 1 |
| 412 | ... return False, max_retries |
| 413 | |
| 414 | >>> # Test retry |
| 415 | >>> success, attempts = retry_until_success( |
| 416 | ... retry_pane, 'echo "OK"', 'OK', max_retries=3, delay=0.2 |
| 417 | ... ) |
| 418 | >>> success |
| 419 | True |
| 420 | >>> attempts |
| 421 | 1 |
| 422 | |
| 423 | >>> # Clean up |
| 424 | >>> retry_window.kill() |
| 425 | ``` |
| 426 | |
| 427 | ## Agentic workflow patterns |
| 428 | |
| 429 | The patterns so far drive one command at a time. The two below compose them into |
| 430 | longer sequences that one pane runs end to end — reach for these when a task is |
| 431 | genuinely a pipeline of steps, not a single call. |
| 432 | |
| 433 | ### Task queue processor |
| 434 | |
| 435 | A task queue runs a list of commands in order, waiting for each to finish before |
| 436 | starting the next. You tag every task with an indexed marker so you know exactly |
| 437 | which step you're waiting on, and you collect a pass/fail result per task. |
| 438 | |
| 439 | ```python |
| 440 | >>> import time |
| 441 | |
| 442 | >>> queue_window = session.new_window(window_name='queue', attach=False) |
| 443 | >>> queue_pane = queue_window.active_pane |
| 444 | |
| 445 | >>> def process_task_queue(pane, tasks, completion_marker='TASK_DONE'): |
| 446 | ... """Process a queue of tasks sequentially.""" |
| 447 | ... results = [] |
| 448 | ... for i, task in enumerate(tasks): |
| 449 | ... pane.send_keys(f'{task}; echo "{completion_marker}_{i}"') |
| 450 | ... # Wait for this task to complete |
| 451 | ... start = time.time() |
| 452 | ... while time.time() - start < 5.0: |
| 453 | ... output = '\\n'.join(pane.capture_pane()) |
| 454 | ... if f'{completion_marker}_{i}' in output: |
| 455 | ... results.append((i, True)) |
| 456 | ... break |
| 457 | ... time.sleep(0.1) |
| 458 | ... else: |
| 459 | ... results.append((i, False)) |
| 460 | ... return results |
| 461 | |
| 462 | >>> tasks = ['echo "Step 1"', 'echo "Step 2"', 'echo "Step 3"'] |
| 463 | >>> results = process_task_queue(queue_pane, tasks) |
| 464 | >>> all(success for _, success in results) |
| 465 | True |
| 466 | |
| 467 | >>> # Clean up |
| 468 | >>> queue_window.kill() |
| 469 | ``` |
| 470 | |
| 471 | ### State machine runner |
| 472 | |
| 473 | When the next step depends on the previous one finishing, model the work as a state |
| 474 | machine: each state runs a command and waits for the transition marker that unlocks |
| 475 | the next. A per-state timeout keeps a single stuck step from stalling the whole run, |
| 476 | and the history tells you how far you got before it stopped. |
| 477 | |
| 478 | ```python |
| 479 | >>> import time |
| 480 | |
| 481 | >>> state_window = session.new_window(window_name='state-machine', attach=False) |
| 482 | >>> state_pane = state_window.active_pane |
| 483 | |
| 484 | >>> def run_state_machine(pane, states, timeout_per_state=2.0): |
| 485 | ... """Run through a series of states with transitions.""" |
| 486 | ... current_state = 0 |
| 487 | ... history = [] |
| 488 | ... |
| 489 | ... while current_state < len(states): |
| 490 | ... state_name, command, next_marker = states[current_state] |
| 491 | ... pane.send_keys(command) |
| 492 | ... |
| 493 | ... start = time.time() |
| 494 | ... while time.time() - start < timeout_per_state: |
| 495 | ... output = '\\n'.join(pane.capture_pane()) |
| 496 | ... if next_marker in output: |
| 497 | ... history.append(state_name) |
| 498 | ... current_state += 1 |
| 499 | ... break |
| 500 | ... time.sleep(0.1) |
| 501 | ... else: |
| 502 | ... return history, False # Timeout |
| 503 | ... |
| 504 | ... return history, True |
| 505 | |
| 506 | >>> states = [ |
| 507 | ... ('init', 'echo "INIT_DONE"', 'INIT_DONE'), |
| 508 | ... ('process', 'echo "PROCESS_DONE"', 'PROCESS_DONE'), |
| 509 | ... ('cleanup', 'echo "CLEANUP_DONE"', 'CLEANUP_DONE'), |
| 510 | ... ] |
| 511 | |
| 512 | >>> history, success = run_state_machine(state_pane, states) |
| 513 | >>> success |
| 514 | True |
| 515 | >>> len(history) |
| 516 | 3 |
| 517 | |
| 518 | >>> # Clean up |
| 519 | >>> state_window.kill() |
| 520 | ``` |
| 521 | |
| 522 | ## Best practices |
| 523 | |
| 524 | ### 1. Always use markers for completion detection |
| 525 | |
| 526 | Timing is a guess; a marker is a fact. Instead of sleeping long enough and hoping a |
| 527 | command finished, have it print an explicit marker and poll for that. Your automation |
| 528 | then reacts to what actually happened rather than to a clock. |
| 529 | |
| 530 | ```python |
| 531 | >>> bp_window = session.new_window(window_name='best-practice', attach=False) |
| 532 | >>> bp_pane = bp_window.active_pane |
| 533 | |
| 534 | >>> # Good: Use completion marker |
| 535 | >>> bp_pane.send_keys('long_command; echo "__DONE__"') |
| 536 | |
| 537 | >>> # Then poll for marker |
| 538 | >>> import time |
| 539 | >>> time.sleep(0.2) |
| 540 | >>> '__DONE__' in '\\n'.join(bp_pane.capture_pane()) |
| 541 | True |
| 542 | |
| 543 | >>> bp_window.kill() |
| 544 | ``` |
| 545 | |
| 546 | ### 2. Clean up resources |
| 547 | |
| 548 | Every window and session you create lives on the tmux server until something kills |
| 549 | it. Tear down what you opened when you're done, so a long-running automation process |
| 550 | doesn't accumulate orphaned objects. |
| 551 | |
| 552 | ```python |
| 553 | >>> cleanup_window = session.new_window(window_name='cleanup-demo', attach=False) |
| 554 | >>> cleanup_window # doctest: +ELLIPSIS |
| 555 | Window(@... ...) |
| 556 | |
| 557 | >>> # Do work... |
| 558 | |
| 559 | >>> # Always clean up |
| 560 | >>> cleanup_window.kill() |
| 561 | >>> cleanup_window not in session.windows |
| 562 | True |
| 563 | ``` |
| 564 | |
| 565 | ### 3. Use context managers for automatic cleanup |
| 566 | |
| 567 | Better still, let a `with` block do the cleanup for you. It runs even when the body |
| 568 | raises, which is exactly when manual cleanup tends to get skipped — so the resource |
| 569 | is released whether the work succeeded or blew up. |
| 570 | |
| 571 | ```python |
| 572 | >>> # Context managers ensure cleanup even on exceptions |
| 573 | >>> with session.new_window(window_name='safe-work') as safe_window: |
| 574 | ... pane = safe_window.active_pane |
| 575 | ... # Work happens here |
| 576 | ... pass # Even if exception occurs, window is cleaned up |
| 577 | ``` |
| 578 | |
| 579 | :::{seealso} |
| 580 | - {ref}`pane-interaction` for basic pane operations |
| 581 | - {ref}`workspace-setup` for creating workspace layouts |
| 582 | - {ref}`context_managers` for resource management patterns |
| 583 | - {class}`~libtmux.Pane` for all pane methods |
| 584 | ::: |