| 1 | (pane-interaction)= |
| 2 | |
| 3 | # Pane interaction |
| 4 | |
| 5 | A {class}`~libtmux.Pane` is a live terminal you drive from Python: you type into |
| 6 | it, read back what it printed, resize it, and tear it down when you're finished. |
| 7 | That makes the pane the unit you reach for when automating a shell, testing a |
| 8 | CLI, or orchestrating a terminal workflow. |
| 9 | |
| 10 | Most of that work is two methods — {meth}`~libtmux.Pane.send_keys` to type and |
| 11 | {meth}`~libtmux.Pane.capture_pane` to read the screen back. If those two cover |
| 12 | you, you can stop after the first two sections; everything below is for the |
| 13 | rarer cases — waiting on output, querying a pane's state, resizing, and cleanup. |
| 14 | |
| 15 | To follow along live, open two terminals. |
| 16 | |
| 17 | In the first, start tmux: |
| 18 | |
| 19 | ```console |
| 20 | $ tmux |
| 21 | ``` |
| 22 | |
| 23 | In the second, start `python` (or `ptpython`, if you have it): |
| 24 | |
| 25 | ```console |
| 26 | $ python |
| 27 | ``` |
| 28 | |
| 29 | ## Sending commands |
| 30 | |
| 31 | {meth}`~libtmux.Pane.send_keys` types text into the pane exactly as if you had |
| 32 | typed it at the keyboard, and by default presses Enter so the shell runs it. |
| 33 | That default is what you want most of the time: hand it a command string and it |
| 34 | executes. The arguments below come into play only when you need to type without |
| 35 | running, send characters tmux would otherwise interpret, or invoke send-keys |
| 36 | purely for its flags. |
| 37 | |
| 38 | ### Basic command execution |
| 39 | |
| 40 | ```python |
| 41 | >>> pane = window.split(shell='sh') |
| 42 | |
| 43 | >>> pane.send_keys('echo "Hello from libtmux"') |
| 44 | |
| 45 | >>> import time; time.sleep(0.1) # Allow command to execute |
| 46 | |
| 47 | >>> output = pane.capture_pane() |
| 48 | >>> 'Hello from libtmux' in '\\n'.join(output) |
| 49 | True |
| 50 | ``` |
| 51 | |
| 52 | ### Send without pressing Enter |
| 53 | |
| 54 | Sometimes you want the text sitting at the prompt without running it — to stage |
| 55 | a command, or to feed a keystroke a running program is waiting on. Pass |
| 56 | `enter=False` to type without pressing Enter: |
| 57 | |
| 58 | ```python |
| 59 | >>> pane.send_keys('echo "waiting"', enter=False) |
| 60 | |
| 61 | >>> # Text is typed but not executed |
| 62 | >>> output = pane.capture_pane() |
| 63 | >>> 'waiting' in '\\n'.join(output) |
| 64 | True |
| 65 | ``` |
| 66 | |
| 67 | When you're ready to run it, press Enter on its own with |
| 68 | {meth}`~libtmux.Pane.enter`: |
| 69 | |
| 70 | ```python |
| 71 | >>> import time |
| 72 | |
| 73 | >>> # First type something without pressing Enter |
| 74 | >>> pane.send_keys('echo "execute me"', enter=False) |
| 75 | |
| 76 | >>> pane.enter() # doctest: +ELLIPSIS |
| 77 | Pane(%... Window(@... ..., Session($... ...))) |
| 78 | |
| 79 | >>> time.sleep(0.2) |
| 80 | |
| 81 | >>> output = pane.capture_pane() |
| 82 | >>> 'execute me' in '\\n'.join(output) |
| 83 | True |
| 84 | ``` |
| 85 | |
| 86 | ### Literal mode for special characters |
| 87 | |
| 88 | Both tmux and your shell interpret certain characters. Pass `literal=True` to |
| 89 | send them through untouched, so a tab or escape arrives as the literal byte |
| 90 | rather than a key tmux acts on: |
| 91 | |
| 92 | ```python |
| 93 | >>> import time |
| 94 | |
| 95 | >>> pane.send_keys('echo "Tab:\\tNewline:\\n"', literal=True) |
| 96 | |
| 97 | >>> time.sleep(0.1) |
| 98 | ``` |
| 99 | |
| 100 | ### Suppress shell history |
| 101 | |
| 102 | Pass `suppress_history=True` to prepend a space before the command. In a shell |
| 103 | configured to ignore space-prefixed lines, that keeps the command out of your |
| 104 | history — useful when the command carries a secret: |
| 105 | |
| 106 | ```python |
| 107 | >>> import time |
| 108 | |
| 109 | >>> pane.send_keys('echo "secret command"', suppress_history=True) |
| 110 | |
| 111 | >>> time.sleep(0.1) |
| 112 | ``` |
| 113 | |
| 114 | ### Flag-only invocation |
| 115 | |
| 116 | Sometimes you want send-keys only for its side effects — resetting the pane or |
| 117 | repeating the last key — and have no text to type. Pass `cmd=None` to invoke it |
| 118 | for the flags alone: |
| 119 | |
| 120 | ```python |
| 121 | >>> # Repeat the last key 5 times (-N 5) |
| 122 | >>> pane.send_keys(cmd=None, repeat=5) |
| 123 | |
| 124 | >>> # Reset the pane to default state (-R) |
| 125 | >>> pane.send_keys(cmd=None, reset=True) |
| 126 | ``` |
| 127 | |
| 128 | `cmd=None` requires at least one of `reset=True`, `repeat=N`, or |
| 129 | `copy_mode_cmd=...`; calling it with no flag raises `ValueError` to |
| 130 | prevent silent no-ops. |
| 131 | |
| 132 | ## Capturing output |
| 133 | |
| 134 | {meth}`~libtmux.Pane.capture_pane` reads the pane's screen back to you as a list |
| 135 | of lines — one string per row, top to bottom. With no arguments you get the |
| 136 | visible screen, which is what most reads want. The parameters below extend that |
| 137 | reach: into scrollback, keeping color, stitching wrapped lines, or preserving |
| 138 | spacing. Reach for them only when a plain capture drops something you need. |
| 139 | |
| 140 | ### Basic capture |
| 141 | |
| 142 | ```python |
| 143 | >>> import time |
| 144 | |
| 145 | >>> pane.send_keys('echo "Line 1"; echo "Line 2"; echo "Line 3"') |
| 146 | |
| 147 | >>> time.sleep(0.1) |
| 148 | |
| 149 | >>> output = pane.capture_pane() |
| 150 | >>> isinstance(output, list) |
| 151 | True |
| 152 | >>> any('Line 2' in line for line in output) |
| 153 | True |
| 154 | ``` |
| 155 | |
| 156 | ### Capture with line ranges |
| 157 | |
| 158 | By default you read the visible screen. Pass `start` and `end` to widen or |
| 159 | narrow that window — negative numbers count back from the visible region, and |
| 160 | `'-'` reaches the start of history or the current line: |
| 161 | |
| 162 | ```python |
| 163 | >>> # Capture last 5 lines of visible pane |
| 164 | >>> recent = pane.capture_pane(start=-5, end='-') |
| 165 | >>> isinstance(recent, list) |
| 166 | True |
| 167 | |
| 168 | >>> # Capture from start of history to current |
| 169 | >>> full_history = pane.capture_pane(start='-', end='-') |
| 170 | >>> len(full_history) >= 0 |
| 171 | True |
| 172 | ``` |
| 173 | |
| 174 | ### Capture with ANSI escape sequences |
| 175 | |
| 176 | A plain capture strips color and formatting, handing you clean text. When you |
| 177 | need the styling instead — to assert a prompt really printed in red — pass |
| 178 | `escape_sequences=True` to keep the ANSI codes intact: |
| 179 | |
| 180 | ```python |
| 181 | >>> import time |
| 182 | |
| 183 | >>> pane.send_keys('printf "\\033[31mRED\\033[0m \\033[32mGREEN\\033[0m"') |
| 184 | >>> time.sleep(0.1) |
| 185 | |
| 186 | >>> # Capture with ANSI codes stripped (default) |
| 187 | >>> output = pane.capture_pane() |
| 188 | >>> 'RED' in '\\n'.join(output) |
| 189 | True |
| 190 | |
| 191 | >>> # Capture with ANSI escape sequences preserved |
| 192 | >>> colored_output = pane.capture_pane(escape_sequences=True) |
| 193 | >>> isinstance(colored_output, list) |
| 194 | True |
| 195 | ``` |
| 196 | |
| 197 | ### Join wrapped lines |
| 198 | |
| 199 | A line longer than the pane wraps onto several rows, and a plain capture returns |
| 200 | it as several strings. Pass `join_wrapped=True` to stitch those rows back into |
| 201 | one logical line: |
| 202 | |
| 203 | ```python |
| 204 | >>> import time |
| 205 | |
| 206 | >>> # Send a very long line that will wrap |
| 207 | >>> pane.send_keys('echo "' + 'x' * 200 + '"') |
| 208 | >>> time.sleep(0.1) |
| 209 | |
| 210 | >>> # Capture with wrapped lines joined |
| 211 | >>> output = pane.capture_pane(join_wrapped=True) |
| 212 | >>> isinstance(output, list) |
| 213 | True |
| 214 | ``` |
| 215 | |
| 216 | ### Preserve trailing spaces |
| 217 | |
| 218 | By default, trailing spaces are trimmed. Use `preserve_trailing=True` to keep them: |
| 219 | |
| 220 | ```python |
| 221 | >>> import time |
| 222 | |
| 223 | >>> pane.send_keys('printf "text \\n"') # 3 trailing spaces |
| 224 | >>> time.sleep(0.1) |
| 225 | |
| 226 | >>> # Capture with trailing spaces preserved |
| 227 | >>> output = pane.capture_pane(preserve_trailing=True) |
| 228 | >>> isinstance(output, list) |
| 229 | True |
| 230 | ``` |
| 231 | |
| 232 | ### Capture flags summary |
| 233 | |
| 234 | The full set of capture flags, and the tmux flag each one maps to: |
| 235 | |
| 236 | | Parameter | tmux Flag | Description | |
| 237 | |-----------|-----------|-------------| |
| 238 | | `escape_sequences` | `-e` | Include ANSI escape sequences (colors, attributes) | |
| 239 | | `escape_non_printable` | `-C` | Escape non-printable chars as octal `\xxx` | |
| 240 | | `join_wrapped` | `-J` | Join wrapped lines back together | |
| 241 | | `preserve_trailing` | `-N` | Preserve trailing spaces at line ends | |
| 242 | | `trim_trailing` | `-T` | Trim trailing empty positions (tmux 3.4+) | |
| 243 | | `pending` | `-P` | Dump the unprocessed input buffer instead of the screen | |
| 244 | |
| 245 | :::{note} |
| 246 | The `trim_trailing` parameter requires tmux 3.4+. If used with an older version, |
| 247 | a warning is issued and the flag is ignored. |
| 248 | ::: |
| 249 | |
| 250 | ### Capturing the pending input buffer |
| 251 | |
| 252 | For the rarer case where you need what tmux has read but not yet drawn, pass |
| 253 | `pending=True`. It dumps bytes tmux has buffered in its parser but |
| 254 | not yet committed to the pane's terminal — input the tmux process read |
| 255 | from the pane's PTY but hasn't fed through its escape-sequence parser |
| 256 | into the visible screen. Use it to inspect partial control sequences |
| 257 | mid-write. |
| 258 | |
| 259 | ```python |
| 260 | >>> pending = pane.capture_pane(pending=True) |
| 261 | >>> isinstance(pending, list) |
| 262 | True |
| 263 | ``` |
| 264 | |
| 265 | `pending=True` is mutually exclusive with the line-range and screen-mode |
| 266 | flags (`start`, `end`, `escape_sequences`, etc.) — tmux ignores them when |
| 267 | `-P` is set. |
| 268 | |
| 269 | ## Waiting for output |
| 270 | |
| 271 | tmux runs commands asynchronously: {meth}`~libtmux.Pane.send_keys` returns the |
| 272 | moment the keystrokes are sent, not when the command finishes. So when a later |
| 273 | step depends on a command completing, you wait for proof in the output rather |
| 274 | than guessing at a fixed delay. |
| 275 | |
| 276 | The honest cost is that this means polling — capturing the pane on a short |
| 277 | interval until a marker you control appears. It's a busy wait, not an event, but |
| 278 | it's reliable across shells and commands because you're checking the one thing |
| 279 | that matters: what actually printed. |
| 280 | |
| 281 | ### Polling for completion marker |
| 282 | |
| 283 | ```python |
| 284 | >>> import time |
| 285 | |
| 286 | >>> pane.send_keys('sleep 0.2; echo "TASK_COMPLETE"') |
| 287 | |
| 288 | >>> # Poll for completion |
| 289 | >>> for _ in range(30): |
| 290 | ... output = pane.capture_pane() |
| 291 | ... if 'TASK_COMPLETE' in '\\n'.join(output): |
| 292 | ... break |
| 293 | ... time.sleep(0.1) |
| 294 | |
| 295 | >>> 'TASK_COMPLETE' in '\\n'.join(output) |
| 296 | True |
| 297 | ``` |
| 298 | |
| 299 | ### Helper function for waiting |
| 300 | |
| 301 | Wrapping that loop in a helper keeps the pattern out of the way of your actual |
| 302 | logic: |
| 303 | |
| 304 | ```python |
| 305 | >>> import time |
| 306 | |
| 307 | >>> def wait_for_text(pane, text, timeout=5.0): |
| 308 | ... """Wait for text to appear in pane output.""" |
| 309 | ... start = time.time() |
| 310 | ... while time.time() - start < timeout: |
| 311 | ... output = pane.capture_pane() |
| 312 | ... if text in '\\n'.join(output): |
| 313 | ... return True |
| 314 | ... time.sleep(0.1) |
| 315 | ... return False |
| 316 | |
| 317 | >>> pane.send_keys('echo "READY"') |
| 318 | >>> wait_for_text(pane, 'READY', timeout=2.0) |
| 319 | True |
| 320 | ``` |
| 321 | |
| 322 | ## Querying pane state |
| 323 | |
| 324 | {meth}`~libtmux.Pane.display_message` asks tmux to evaluate a format string |
| 325 | against the pane and hand back the result — its size, working directory, process |
| 326 | id, and the rest of tmux's `#{pane_*}` variables. Pass `get_text=True` to get |
| 327 | the answer as a list of strings. |
| 328 | |
| 329 | Each call is a round-trip to tmux, which is exactly what you want for state that |
| 330 | moves as you watch it — dimensions during a resize, the working directory after |
| 331 | a `cd` — since you get a fresh reading rather than a value cached when the object |
| 332 | was built. |
| 333 | |
| 334 | ### Get pane dimensions |
| 335 | |
| 336 | ```python |
| 337 | >>> width = pane.display_message('#{pane_width}', get_text=True) |
| 338 | >>> isinstance(width, list) and len(width) > 0 |
| 339 | True |
| 340 | |
| 341 | >>> height = pane.display_message('#{pane_height}', get_text=True) |
| 342 | >>> isinstance(height, list) and len(height) > 0 |
| 343 | True |
| 344 | ``` |
| 345 | |
| 346 | ### Get pane information |
| 347 | |
| 348 | ```python |
| 349 | >>> # Current working directory |
| 350 | >>> cwd = pane.display_message('#{pane_current_path}', get_text=True) |
| 351 | >>> isinstance(cwd, list) |
| 352 | True |
| 353 | |
| 354 | >>> # Pane ID |
| 355 | >>> pane_id = pane.display_message('#{pane_id}', get_text=True) |
| 356 | >>> pane_id[0].startswith('%') |
| 357 | True |
| 358 | ``` |
| 359 | |
| 360 | ### Common format variables |
| 361 | |
| 362 | A few of the format variables you'll reach for most often: |
| 363 | |
| 364 | | Variable | Description | |
| 365 | |----------|-------------| |
| 366 | | `#{pane_width}` | Pane width in characters | |
| 367 | | `#{pane_height}` | Pane height in characters | |
| 368 | | `#{pane_current_path}` | Current working directory | |
| 369 | | `#{pane_pid}` | PID of the pane's shell | |
| 370 | | `#{pane_id}` | Unique pane ID (e.g., `%0`) | |
| 371 | | `#{pane_index}` | Pane index in window | |
| 372 | |
| 373 | ## Resizing panes |
| 374 | |
| 375 | {meth}`~libtmux.Pane.resize` changes how much of the window a pane occupies. It |
| 376 | covers three needs through one method: set an exact size, nudge a dimension by a |
| 377 | relative amount, or toggle zoom to make the pane fill the window and back. The |
| 378 | result is bounded by the window and the pane's neighbors — tmux grants the space |
| 379 | it can, so treat a resize as a request, not a guarantee. |
| 380 | |
| 381 | ### Resize by specific dimensions |
| 382 | |
| 383 | ```python |
| 384 | >>> # Make pane larger |
| 385 | >>> pane.resize(height=20, width=80) # doctest: +ELLIPSIS |
| 386 | Pane(%... Window(@... ..., Session($... ...))) |
| 387 | ``` |
| 388 | |
| 389 | ### Resize by adjustment |
| 390 | |
| 391 | To grow or shrink a pane relative to its current size, name a direction from |
| 392 | {class}`~libtmux.constants.ResizeAdjustmentDirection` and how far to move: |
| 393 | |
| 394 | ```python |
| 395 | >>> from libtmux.constants import ResizeAdjustmentDirection |
| 396 | |
| 397 | >>> # Increase height by 5 rows |
| 398 | >>> pane.resize(adjustment_direction=ResizeAdjustmentDirection.Up, adjustment=5) # doctest: +ELLIPSIS |
| 399 | Pane(%... Window(@... ..., Session($... ...))) |
| 400 | |
| 401 | >>> # Decrease width by 10 columns |
| 402 | >>> pane.resize(adjustment_direction=ResizeAdjustmentDirection.Left, adjustment=10) # doctest: +ELLIPSIS |
| 403 | Pane(%... Window(@... ..., Session($... ...))) |
| 404 | ``` |
| 405 | |
| 406 | ### Zoom toggle |
| 407 | |
| 408 | Zoom blows a pane up to fill the whole window so you can focus on it, then |
| 409 | restores the layout on the next call. It's a toggle, so the same call both |
| 410 | zooms and unzooms: |
| 411 | |
| 412 | ```python |
| 413 | >>> # Zoom pane to fill window |
| 414 | >>> pane.resize(zoom=True) # doctest: +ELLIPSIS |
| 415 | Pane(%... Window(@... ..., Session($... ...))) |
| 416 | |
| 417 | >>> # Unzoom |
| 418 | >>> pane.resize(zoom=True) # doctest: +ELLIPSIS |
| 419 | Pane(%... Window(@... ..., Session($... ...))) |
| 420 | ``` |
| 421 | |
| 422 | ## Clearing the pane |
| 423 | |
| 424 | {meth}`~libtmux.Pane.clear` wipes the pane's visible screen, leaving a clean |
| 425 | prompt — it runs `reset` in the pane, so it restores terminal state, not just |
| 426 | the screen: |
| 427 | |
| 428 | ```python |
| 429 | >>> pane.clear() # doctest: +ELLIPSIS |
| 430 | Pane(%... Window(@... ..., Session($... ...))) |
| 431 | ``` |
| 432 | |
| 433 | ## Killing panes |
| 434 | |
| 435 | {meth}`~libtmux.Pane.kill` destroys a pane and the process running inside it. |
| 436 | Once killed, the pane is gone from its window, and any {class}`~libtmux.Pane` |
| 437 | object still pointing at it is stale — drop the reference rather than reusing it. |
| 438 | |
| 439 | ```python |
| 440 | >>> # Create a temporary pane |
| 441 | >>> temp_pane = pane.split() |
| 442 | >>> temp_pane in window.panes |
| 443 | True |
| 444 | |
| 445 | >>> # Kill it |
| 446 | >>> temp_pane.kill() |
| 447 | >>> temp_pane not in window.panes |
| 448 | True |
| 449 | ``` |
| 450 | |
| 451 | ### Kill all except current |
| 452 | |
| 453 | Pass `all_except=True` to invert the target — kill every other pane in the |
| 454 | window and keep this one. It's the quick way to collapse a window back to a |
| 455 | single pane: |
| 456 | |
| 457 | ```python |
| 458 | >>> # Setup: create multiple panes |
| 459 | >>> pane.window.resize(height=60, width=120) # doctest: +ELLIPSIS |
| 460 | Window(@... ...) |
| 461 | |
| 462 | >>> keep_pane = pane.split() |
| 463 | >>> extra1 = pane.split() |
| 464 | >>> extra2 = pane.split() |
| 465 | |
| 466 | >>> # Kill all except keep_pane |
| 467 | >>> keep_pane.kill(all_except=True) |
| 468 | |
| 469 | >>> keep_pane in window.panes |
| 470 | True |
| 471 | >>> extra1 not in window.panes |
| 472 | True |
| 473 | >>> extra2 not in window.panes |
| 474 | True |
| 475 | |
| 476 | >>> # Cleanup |
| 477 | >>> keep_pane.kill() |
| 478 | ``` |
| 479 | |
| 480 | ## Practical recipes |
| 481 | |
| 482 | These tie the pieces together into the patterns you'll actually reach for: |
| 483 | running a command and collecting its output, and scanning output for trouble. |
| 484 | Lift them as-is or adapt them — both lean only on the |
| 485 | {meth}`~libtmux.Pane.send_keys` and {meth}`~libtmux.Pane.capture_pane` methods |
| 486 | you've already met. |
| 487 | |
| 488 | ### Recipe: run command and capture output |
| 489 | |
| 490 | ```python |
| 491 | >>> import time |
| 492 | |
| 493 | >>> def run_and_capture(pane, command, marker='__DONE__', timeout=5.0): |
| 494 | ... """Run a command and return its output.""" |
| 495 | ... pane.send_keys(f'{command}; echo {marker}') |
| 496 | ... start = time.time() |
| 497 | ... while time.time() - start < timeout: |
| 498 | ... output = pane.capture_pane() |
| 499 | ... output_str = '\\n'.join(output) |
| 500 | ... if marker in output_str: |
| 501 | ... return output # Return all captured output |
| 502 | ... time.sleep(0.1) |
| 503 | ... raise TimeoutError(f'Command did not complete within {timeout}s') |
| 504 | |
| 505 | >>> result = run_and_capture(pane, 'echo "captured text"', timeout=2.0) |
| 506 | >>> 'captured text' in '\\n'.join(result) |
| 507 | True |
| 508 | ``` |
| 509 | |
| 510 | ### Recipe: check for error patterns |
| 511 | |
| 512 | ```python |
| 513 | >>> import time |
| 514 | |
| 515 | >>> def check_for_errors(pane, error_patterns=None): |
| 516 | ... """Check pane output for error patterns.""" |
| 517 | ... if error_patterns is None: |
| 518 | ... error_patterns = ['error:', 'Error:', 'ERROR', 'failed', 'FAILED'] |
| 519 | ... output = '\\n'.join(pane.capture_pane()) |
| 520 | ... for pattern in error_patterns: |
| 521 | ... if pattern in output: |
| 522 | ... return True |
| 523 | ... return False |
| 524 | |
| 525 | >>> pane.send_keys('echo "All good"') |
| 526 | >>> time.sleep(0.1) |
| 527 | >>> check_for_errors(pane) |
| 528 | False |
| 529 | ``` |
| 530 | |
| 531 | :::{seealso} |
| 532 | - {ref}`api` for the full API reference |
| 533 | - {class}`~libtmux.Pane` for all pane methods |
| 534 | - {ref}`automation-patterns` for advanced orchestration patterns |
| 535 | ::: |