user1532043
user1532043

Reputation: 899

How can I run some command in iTerm session using the Python API

I am trying to write a script that'd do some automation on my iTerm2. I am using the Python API for iTerm since I know nothing about AppleScript.

What I need to do is basically, split the screen is 6 windows and run 6 microservices locally in each of them. I was successfully able to split the screen but I am unable to run a command in any of them.

Thanks in advance.

My existing code is as follow

#!/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()
    else:
        # You can view this message in the script console.
        print("No current window")

    leftOne = app.current_terminal_window.current_tab.current_session
    rightOne = await leftOne.async_split_pane(vertical=True)
    leftTwo = await leftOne.async_split_pane()
    leftThree = await leftOne.async_split_pane()
    rightTwo = await rightOne.async_split_pane()
    rightThree = await rightOne.async_split_pane()

    await leftOne.async_activate()
    await leftOne.as

iterm2.run_until_complete(main)

Upvotes: 5

Views: 2853

Answers (1)

Joseph S.
Joseph S.

Reputation: 495

You can send keystrokes to Sessions using the async_send_text() method.

In your code, the following will execute a command:

leftOne = app.current_terminal_window.current_tab.current_session
await leftOne.async_send_text('whoami\n')

Upvotes: 7

Related Questions