我正在尝试创建一个脚本,该脚本将打开一个
iTerm2
窗口,将其垂直分成 3 个窗格,并在每个窗格中运行一些命令。
这是我迄今为止的尝试:
tell application "iTerm2"
activate
-- Create main window
create window with default profile
tell current session of current window
set name to "frontend"
write text "cd ~/Documents/frontendDir"
split vertically with default profile
end tell
tell second session of current window -- ERROR HERE
set name to "backend"
write text "cd ~/Documents/backendDir"
split vertically with default profile
end tell
tell third session of current window
set name to "apollo-server"
write text "cd ~/Documents/GitHub/apolloDir"
end tell
end tell
关于创建
frontend
的第一部分似乎可以正常工作,因为窗口已正确打开并且命令 cd ~/Documents/frontendDir
在其中正确执行。该窗口也会垂直分割一次,因为我很确定当我尝试访问窗口的第二个窗格时它会停止执行。
我收到此错误:
iTerm got an error: Can’t get session 2 of current window
提前致谢
iTerm
session
对象包含在 tabs
中,而不是 windows
中。因此,正如您在下面的脚本片段中看到的,我通过 current tab
的 current window
引用了要写入的每个会话:
tell application "iTerm"
activate
set W to current window
if W = missing value then set W to create window with default profile
tell W's current session
split vertically with default profile
split vertically with default profile
end tell
set T to W's current tab
write T's session 1 text "cd ~/Desktop"
write T's session 2 text "cd ~/Downloads"
write T's session 3 text "cd ~/Documents"
end tell
据我所知,你不能设置
name
的 session
属性;它被设置为会话框架的标题。您可以通过索引引用每个 session
(就像我在这里所做的那样);它的 id
属性;或其 tty
属性;所有这些都是独特的价值。
如您所见,索引似乎是按会话的创建排序的:
您可以使用Python脚本:
import iterm2
async def main(connection):
app = await iterm2.async_get_app(connection)
window = app.current_terminal_window
# Define base path and project name variables
base_path = '/Users/username/somefolder'
project_name = 'projectname'
if window is not None:
# Create a new tab
tab = await window.async_create_tab()
# Store a reference to the left pane (initial session)
left_panel = tab.current_session
# Execute command in the top-left pane
cmd_top_left = f'cd {base_path}; ./docker-{project_name}-run-kernel\n'
await left_panel.async_send_text(cmd_top_left)
# Create a right pane by splitting the left one vertically
right_panel = await left_panel.async_split_pane(vertical=True)
# Split the right pane into top and bottom panes
bottom_right_panel = await right_panel.async_split_pane(vertical=False)
# Execute command in the top-right pane
cmd_top_right = f'cd {base_path}/{project_name}\n'
await right_panel.async_send_text(cmd_top_right)
# Execute command in the bottom-right pane
cmd_bottom_right = f'docker exec -it {project_name}-puma-1 bash\n'
await bottom_right_panel.async_send_text(cmd_bottom_right)
# Split the left pane into top and bottom using the stored reference
bottom_left_panel = await left_panel.async_split_pane(vertical=False)
# Execute command in the bottom-left pane
cmd_bottom_left = f'cd {base_path}; ./docker-{project_name}-run-rails; cd {base_path}/{project_name}\n'
await bottom_left_panel.async_send_text(cmd_bottom_left)
else:
print("No current window")
iterm2.run_until_complete(main)