How do I activate venv in each new terminal in a Dev Container?
Asked Answered
M

1

9

I'm trying to create a devcontainer.json that will create a Python virtual environment and activate it in the terminal immediately.

I use postCreateCommand to create the environment, and that seems to work:

 "postCreateCommand": "python3 -m venv .venv",

But I haven't figured out how to get the terminal to always activate it. I've tried adding this setting:

            "settings": {
                "python.terminal.activateEnvInCurrentTerminal": true
            }

As well as post*Commands:

  "postAttachCommand": ". .venv/bin/activate",
  "postStartCommand": ". .venv/bin/activate",
  "postCreateCommand": ". .venv/bin/activate",

They don't seem to reliably activate it. I think postAttachCommand worked sometimes, but not always.

Moonshot answered 10/2, 2023 at 20:7 Comment(2)
Did you figure this out? I'm trying to set up a devcontainer with venv as well, but not sure how to do it properly. Do you define anything in the Dockerfile as well or do you only use the postCreateCommand in the devcontainer.json file?Quarterback
I ended up using a combo of postCreateCommand and postAttachCommand: github.com/pamelafox/fastapi-on-azure-functions/blob/main/…Moonshot
N
4

When you also set the defaultInterpreterPath-setting it works as expected:

"settings": {
    "python.terminal.activateEnvInCurrentTerminal": true,
    "python.defaultInterpreterPath": ".venv/bin/python",
}
Nard answered 14/9, 2023 at 7:32 Comment(2)
Mine still doesn't autoactivate with above settings.jsonTweedy
Note that settings has deprecated and replaced by customizations/vscode/settings, see also https://mcmap.net/q/1319088/-vscode-remote-container-default-python-interpreterLaplante

© 2022 - 2024 — McMap. All rights reserved.