Skip to content

Instantly share code, notes, and snippets.

@ekowcharles
Last active May 4, 2022 16:40
Show Gist options
  • Save ekowcharles/e43d0c79adb9859a4cd251f63607020c to your computer and use it in GitHub Desktop.
Save ekowcharles/e43d0c79adb9859a4cd251f63607020c to your computer and use it in GitHub Desktop.
Automate Tabs & Commands in iTerm2
#!/usr/bin/env python3.7
# As described by Daniela Baron -> https://danielabaron.me/blog/iterm-automation/
#
# The contents of a sample commands definition file may look like so:
# [
# {
# "title": "usrv",
# "panes": [
# {
# "commands": [
# "cd /Volumes/Data/workspaces/awesome-app/usrv",
# "make clean",
# "make run"
# ]
# },
# {
# "commands": [
# "cd /Volumes/Data/workspaces/awesome-app",
# "code ."
# ]
# }
# ]
# }
# ]
#
# The above definition creates two panes, in one pane I change to my project directory and launch one of my applications.
# In the other pane I change to my workspace directory and launch Visual Studio code. I use this pane for CI commands later.
import iterm2
import json
async def main(connection):
app = await iterm2.async_get_app(connection)
window = app.current_terminal_window
if window is not None:
with open('/absolute/path/to/your/commands/definition/file.json', 'r') as file:
data = json.load(file)
for tab_def in data:
tab = await window.async_create_tab()
await tab.async_activate()
await tab.async_set_title(tab_def["title"])
session = tab.current_session
for i, pane_def in enumerate(tab_def["panes"]):
if i == 0:
for command in pane_def["commands"]:
await session.async_send_text(f"{command}\n")
continue
pane = await session.async_split_pane(vertical=False)
for command in pane_def["commands"]:
await pane.async_activate()
await pane.async_send_text(f"{command}\n")
else:
print("No current window")
iterm2.run_until_complete(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment