|
| 1 | +--- |
| 2 | +orphan: true |
| 3 | +--- |
| 4 | + |
| 5 | +# Advanced Scripting |
| 6 | + |
| 7 | +libtmux enables sophisticated scripting of tmux operations, allowing developers to create robust tools and workflows. |
| 8 | + |
| 9 | +## Complex Window and Pane Layouts |
| 10 | + |
| 11 | +You can create intricate layouts with precise control over window and pane placement: |
| 12 | + |
| 13 | +```python |
| 14 | +import libtmux |
| 15 | + |
| 16 | +server = libtmux.Server() |
| 17 | +session = server.new_session(session_name="complex-layout") |
| 18 | + |
| 19 | +# Create main window |
| 20 | +main = session.new_window(window_name="main-window") |
| 21 | + |
| 22 | +# Create side pane (vertical split) |
| 23 | +side_pane = main.split_window(vertical=True) |
| 24 | + |
| 25 | +# Create bottom pane (horizontal split from main pane) |
| 26 | +bottom_pane = main.attached_pane.split_window(vertical=False) |
| 27 | + |
| 28 | +# Create a grid layout in another window |
| 29 | +grid_window = session.new_window(window_name="grid") |
| 30 | +top_left = grid_window.attached_pane |
| 31 | +top_right = top_left.split_window(vertical=True) |
| 32 | +bottom_left = top_left.split_window(vertical=False) |
| 33 | +bottom_right = top_right.split_window(vertical=False) |
| 34 | + |
| 35 | +# Now you can send commands to each pane |
| 36 | +top_left.send_keys("echo 'Top Left'", enter=True) |
| 37 | +top_right.send_keys("echo 'Top Right'", enter=True) |
| 38 | +bottom_left.send_keys("echo 'Bottom Left'", enter=True) |
| 39 | +bottom_right.send_keys("echo 'Bottom Right'", enter=True) |
| 40 | +``` |
| 41 | + |
| 42 | +## Reactive Scripts |
| 43 | + |
| 44 | +Create scripts that react to tmux events or monitor state: |
| 45 | + |
| 46 | +```python |
| 47 | +import libtmux |
| 48 | +import time |
| 49 | + |
| 50 | +server = libtmux.Server() |
| 51 | +session = server.find_where({"session_name": "monitored-session"}) |
| 52 | + |
| 53 | +if not session: |
| 54 | + print("Session not found!") |
| 55 | + exit(1) |
| 56 | + |
| 57 | +def monitor_pane_count(): |
| 58 | + """Monitor the number of panes and react to changes""" |
| 59 | + initial_pane_count = len(session.list_windows()[0].list_panes()) |
| 60 | + print(f"Starting monitor with {initial_pane_count} panes") |
| 61 | + |
| 62 | + while True: |
| 63 | + time.sleep(5) # Check every 5 seconds |
| 64 | + current_pane_count = len(session.list_windows()[0].list_panes()) |
| 65 | + |
| 66 | + if current_pane_count > initial_pane_count: |
| 67 | + print(f"New pane detected! ({current_pane_count} total)") |
| 68 | + # React to new pane - perhaps log it or configure it |
| 69 | + newest_pane = session.list_windows()[0].list_panes()[-1] |
| 70 | + newest_pane.send_keys("echo 'This pane was auto-configured'", enter=True) |
| 71 | + |
| 72 | + elif current_pane_count < initial_pane_count: |
| 73 | + print(f"Pane closed! ({current_pane_count} remaining)") |
| 74 | + # React to closed pane |
| 75 | + |
| 76 | + initial_pane_count = current_pane_count |
| 77 | + |
| 78 | +# Use in a script |
| 79 | +if __name__ == "__main__": |
| 80 | + try: |
| 81 | + monitor_pane_count() |
| 82 | + except KeyboardInterrupt: |
| 83 | + print("Monitoring stopped") |
| 84 | +``` |
| 85 | + |
| 86 | +## Working with Command Output |
| 87 | + |
| 88 | +libtmux allows you to easily capture and process command output: |
| 89 | + |
| 90 | +```python |
| 91 | +import libtmux |
| 92 | + |
| 93 | +server = libtmux.Server() |
| 94 | +session = server.new_session(session_name="command-output") |
| 95 | +window = session.attached_window |
| 96 | + |
| 97 | +# Send a command and capture its output |
| 98 | +window.send_keys("ls -la", enter=True) |
| 99 | + |
| 100 | +# Wait for command to complete |
| 101 | +import time |
| 102 | +time.sleep(1) |
| 103 | + |
| 104 | +# Capture the pane content |
| 105 | +output = window.attached_pane.capture_pane() |
| 106 | + |
| 107 | +# Process the output |
| 108 | +for line in output: |
| 109 | + if "total " in line: |
| 110 | + print(f"Directory size summary: {line}") |
| 111 | + break |
| 112 | + |
| 113 | +# Execute a tmux command directly and process its result |
| 114 | +running_sessions = server.cmd("list-sessions", "-F", "#{session_name}").stdout |
| 115 | +print(f"Current sessions: {running_sessions}") |
| 116 | +``` |
| 117 | + |
| 118 | +## State Management |
| 119 | + |
| 120 | +Implement state tracking for your tmux sessions: |
| 121 | + |
| 122 | +```python |
| 123 | +import libtmux |
| 124 | +import json |
| 125 | +import os |
| 126 | +from datetime import datetime |
| 127 | + |
| 128 | +class TmuxStateManager: |
| 129 | + def __init__(self, state_file="~/.tmux_state.json"): |
| 130 | + self.state_file = os.path.expanduser(state_file) |
| 131 | + self.server = libtmux.Server() |
| 132 | + self.state = self._load_state() |
| 133 | + |
| 134 | + def _load_state(self): |
| 135 | + if os.path.exists(self.state_file): |
| 136 | + with open(self.state_file, 'r') as f: |
| 137 | + return json.load(f) |
| 138 | + return {"sessions": {}, "last_update": None} |
| 139 | + |
| 140 | + def _save_state(self): |
| 141 | + self.state["last_update"] = datetime.now().isoformat() |
| 142 | + with open(self.state_file, 'w') as f: |
| 143 | + json.dump(self.state, f, indent=2) |
| 144 | + |
| 145 | + def update_session_state(self, session_name): |
| 146 | + """Record information about a session""" |
| 147 | + session = self.server.find_where({"session_name": session_name}) |
| 148 | + if not session: |
| 149 | + return False |
| 150 | + |
| 151 | + windows_info = [] |
| 152 | + for window in session.windows: |
| 153 | + panes_info = [] |
| 154 | + for pane in window.panes: |
| 155 | + panes_info.append({ |
| 156 | + "pane_id": pane.pane_id, |
| 157 | + "pane_index": pane.pane_index, |
| 158 | + "current_path": pane.current_path, |
| 159 | + "current_command": pane.current_command |
| 160 | + }) |
| 161 | + |
| 162 | + windows_info.append({ |
| 163 | + "window_id": window.window_id, |
| 164 | + "window_name": window.window_name, |
| 165 | + "panes": panes_info |
| 166 | + }) |
| 167 | + |
| 168 | + self.state["sessions"][session_name] = { |
| 169 | + "session_id": session.session_id, |
| 170 | + "created_at": datetime.now().isoformat(), |
| 171 | + "windows": windows_info |
| 172 | + } |
| 173 | + |
| 174 | + self._save_state() |
| 175 | + return True |
| 176 | + |
| 177 | + def restore_session(self, session_name): |
| 178 | + """Attempt to restore a session based on saved state""" |
| 179 | + if session_name not in self.state["sessions"]: |
| 180 | + return False |
| 181 | + |
| 182 | + saved_session = self.state["sessions"][session_name] |
| 183 | + # Implementation of session restoration logic here |
| 184 | + |
| 185 | + return True |
| 186 | +``` |
| 187 | + |
| 188 | +## Integration with External APIs |
| 189 | + |
| 190 | +Combine libtmux with external APIs for powerful automation: |
| 191 | + |
| 192 | +```python |
| 193 | +import libtmux |
| 194 | +import requests |
| 195 | +import json |
| 196 | + |
| 197 | +def deploy_and_monitor(repo_name, branch="main"): |
| 198 | + # Start a new deployment session |
| 199 | + server = libtmux.Server() |
| 200 | + session = server.new_session(session_name=f"deploy-{repo_name}") |
| 201 | + |
| 202 | + # Window for deployment log |
| 203 | + deploy_window = session.attached_window |
| 204 | + deploy_window.rename_window("deployment") |
| 205 | + |
| 206 | + # Window for API responses |
| 207 | + api_window = session.new_window(window_name="api-status") |
| 208 | + |
| 209 | + # Trigger deployment via API |
| 210 | + deploy_window.send_keys(f"echo 'Starting deployment of {repo_name}:{branch}'", enter=True) |
| 211 | + response = requests.post( |
| 212 | + "https://api.example.com/deployments", |
| 213 | + json={"repository": repo_name, "branch": branch}, |
| 214 | + headers={"Authorization": "Bearer YOUR_TOKEN"} |
| 215 | + ) |
| 216 | + |
| 217 | + # Display API response |
| 218 | + deployment_id = response.json().get("deployment_id") |
| 219 | + api_window.send_keys(f"echo 'Deployment triggered: {deployment_id}'", enter=True) |
| 220 | + |
| 221 | + # Poll status API |
| 222 | + for _ in range(10): # Check 10 times |
| 223 | + status_response = requests.get( |
| 224 | + f"https://api.example.com/deployments/{deployment_id}", |
| 225 | + headers={"Authorization": "Bearer YOUR_TOKEN"} |
| 226 | + ) |
| 227 | + status = status_response.json().get("status") |
| 228 | + api_window.send_keys(f"echo 'Current status: {status}'", enter=True) |
| 229 | + |
| 230 | + if status in ["complete", "failed"]: |
| 231 | + break |
| 232 | + |
| 233 | + # Wait before checking again |
| 234 | + import time |
| 235 | + time.sleep(30) |
| 236 | + |
| 237 | + # Final deployment result |
| 238 | + deploy_window.send_keys(f"echo 'Deployment {deployment_id} finished with status: {status}'", enter=True) |
| 239 | + |
| 240 | + return deployment_id, status |
| 241 | +``` |
| 242 | + |
| 243 | +## Debugging Tips |
| 244 | + |
| 245 | +When scripting with libtmux, consider these debugging approaches: |
| 246 | + |
| 247 | +1. Use `session.cmd('display-message', 'Debug message')` to display messages in the tmux client |
| 248 | +2. Capture pane content with `pane.capture_pane()` to see the current state |
| 249 | +3. Use Python's logging module to track script execution |
| 250 | +4. Add print statements and redirect your script's output to a file for later inspection |
| 251 | +5. When testing complex scripts, use a dedicated testing session to avoid affecting your main workflow |
| 252 | +``` |
0 commit comments