Python API - How do I set an environment variable prior to running the command?

193 views
Skip to first unread message

Jon D

unread,
Sep 14, 2020, 12:19:09 PM9/14/20
to iterm2-discuss
How do I set an environment variable prior to running the command?

I'm trying to send an environment prior to starting zsh.

I have 4 virtual envs that I need to source into the current session to set the environment (python virtualenv / nodeenv).

This works from the command line, but not from the python api:
I added the following to ~/.zshrc...

```
if [[ -n "$ZVENV" ]]; then
  source "$ZVENV"
fi
```

...and start the command (from the command line) as such:

```
ZVENV=/Users/jon/work/project1/nenv/bin/activate /bin/zsh
```

When I send that as a command to iterm2, the session drops immediately. I can't read the output on the session because I suppressed the dialog and couldn't read under it anyways.

```
command_to_run = "ZVENV=/Users/jon/work/project1/nenv/bin/activate /bin/zsh"
window = await iterm2.Window.async_create(connection, command=command_to_run)
```

How do I set an environment variable prior to running the command?

Alternatively, is there a way to "send text" to the default profile when I create the tab - there is this option in profile setup to "Send text at start:" and that would work if I wanted to manage a ton of profiles, which I don't.

Thanks

George Nachman

unread,
Sep 17, 2020, 2:41:54 AM9/17/20
to iterm2-...@googlegroups.com
There is no API for setting environment variables for a new session. I’ve been meaning to add this to the UI forever, and I should add it to the Python API as well when I get to it.

However, you can send text to a newly created session.

```
window = await iterm2.Window.async_create(connection)
await window.current_tab.current_session.async_send_text("ZVENV=blah blah\n”)
```

The reason the session is closing immediately is that the way commands are run does not accept an environment variable at the beginning, as it does when you run it from bash or zsh. If you want to be able to see the error message, change "Prefs > Profiles > Session > After a session ends” to “No action”.

--
You received this message because you are subscribed to the Google Groups "iterm2-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to iterm2-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/iterm2-discuss/6496b353-e2c4-4a06-8cf0-5ff2ca1d785bn%40googlegroups.com.

Tom Feist-Hassan

unread,
Sep 28, 2020, 7:40:25 AM9/28/20
to iterm2-...@googlegroups.com
A quick fiddle suggests something like

```
await iterm2.Window.async_create(conn, command='/usr/bin/env SOME_ENV=testing ANOTHER_VAR=testing2 /usr/local/bin/zsh --interactive')
```

should work, using `/usr/bin/env` to set things up before invoking your actual command. Haven't tested with venv activate scripts though.

Reply all
Reply to author
Forward
0 new messages