Created
March 14, 2022 11:34
-
-
Save mairas/928a8abcd61fcadb53c1f04582218227 to your computer and use it in GitHub Desktop.
Launch a new iTerm2 window from command line with optional custom path and command arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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), | |
default=os.getcwd(), | |
) | |
@click.argument("command", type=str, default="") | |
def main(cwd, command): | |
""" | |
Authors: | |
Sandro Braun - 2021 | |
Matti Airas - 2022 | |
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() | |
# create a new local write-only profile | |
custom = iterm2.LocalWriteOnlyProfile() | |
# set CWD for the new profile | |
initial_wd_mode = iterm2.profile.InitialWorkingDirectory( | |
iterm2.profile.InitialWorkingDirectory.INITIAL_WORKING_DIRECTORY_CUSTOM | |
) | |
custom.set_initial_directory_mode(initial_wd_mode) | |
custom.set_custom_directory(os.path.abspath(cwd)) | |
# set command for the new profile | |
if command != "": | |
custom.set_command(command) | |
custom.set_use_custom_command("Yes") | |
await iterm2.Window.async_create(connection, profile_customizations=custom) | |
iterm2.run_until_complete(_main, True) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment