'iTerm2 3.3 Python API -- how to create a 2x2 grid of sessions?

I am trying to write a Python script to create a new tab with a 2x2 grid of sessions but I am finding the docs to be lacking.

The following is what I have so far (which doesn't work), can any one help?

#!/usr/bin/env python3.7

import iterm2
# This script was created with the "basic" environment which does not support adding dependencies
# with pip.

async def main(connection):
    # Your code goes here. Here's a bit of example code that adds a tab to the current window:
    app = await iterm2.async_get_app(connection)
    window = app.current_terminal_window
    if window is not None:
        await window.async_create_tab()
        session = tab.current_session

        await session.async_split_pane()

        await tab.async_select_pane_in_direction(iterm2.NavigationDirection.BELOW)
        await session.async_split_pane()

        # await tab.async_select_pane_in_direction(iterm2.NavigationDirection.ABOVE)
        # await session.async_split_pane()
    else:
        print("No current window")

iterm2.run_until_complete(main)


Solution 1:[1]

Instead of using async_select_pane_in_direction to move b/w windows, you can store the output of await session_1_1.async_split_pan and then easily create windows of your choice.

For managing many windows, instead of writing it multiple times, put it in the loop.

#!/usr/bin/env python3.7

import iterm2

# This script was created with the "basic" environment which does not support adding dependencies
# with pip.


async def main(connection):
    # Your code goes here. Here's a bit of example code that adds a tab to the current window:
    app = await iterm2.async_get_app(connection)
    window = app.current_terminal_window
    if window is not None:
        main = await window.async_create_tab()
        await main.async_activate()
        session_1_1 = main.current_session
        session_2_1 = await session_1_1.async_split_pane(vertical=True)
        session_1_2 = await session_1_1.async_split_pane(vertical=False)
        session_2_2 = await session_2_1.async_split_pane(vertical=False)

        await session_1_1.async_send_text('echo "This is at pos 1_1"\n')
        await session_2_1.async_send_text('echo "This is at pos 2_1"\n')
        await session_1_2.async_send_text('echo "This is at pos 1_2"\n')
        await session_2_2.async_send_text('echo "This is at pos 2_2"\n')
    else:
        print("No current window")


iterm2.run_until_complete(main)

Result

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rahul Kumar