Skip to content

Instantly share code, notes, and snippets.

@theRealSuperMario
Created April 4, 2021 13:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theRealSuperMario/31f7429d9c805165e1dd30ccbd744ec7 to your computer and use it in GitHub Desktop.
Save theRealSuperMario/31f7429d9c805165e1dd30ccbd744ec7 to your computer and use it in GitHub Desktop.
Run a command in a new iTerm tab
#!/usr/bin/env python3
import iterm2
import AppKit
import click
import os
@click.command()
@click.argument(
"cwd", type=click.Path(exists=True, file_okay=False, dir_okay=True)
)
@click.argument(
"command", type=str
)
def main(cwd, command):
"""
Author: Sandro Braun - 2021
create new iterm tab and run command
Parameters
----------
cwd : [str]
directory to cd into before running command
command: [str]
command to exectue, i.e. the full command will be 'cd $path; command'
Examples
--------
./iterm.py ~/Desktop vi
References
----------
* https://iterm2.com/python-api/examples/launch_and_run.html
* https://raymondjulin.com/blog/exploring-the-iterm2-python-api
"""
# Launch the app
AppKit.NSWorkspace.sharedWorkspace().launchApplication_("iTerm2")
async def _main(connection):
app = await iterm2.async_get_app(connection)
# Foreground the app
await app.async_activate()
window = app.current_window
if window is not None:
new_tab = await window.async_create_tab()
cmd = f"/bin/zsh -l -c 'cd {cwd};{command}'\n"
await new_tab.async_select()
await new_tab.current_session.async_send_text(cmd)
iterm2.run_until_complete(_main, True)
if __name__ == "__main__":
main()
@mairas
Copy link

mairas commented Mar 14, 2022

Thanks for this! I took your work and modified it slightly to make the cwd and command args optional. They are now delivered using a LocalWriteOnlyProfile. See here:

https://gist.github.com/mairas/928a8abcd61fcadb53c1f04582218227

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment