4

I'm working on a data science project for which I have a repo. I would like to create a python virtual environment in the codespace when it is initialized so that I can execute code in Jupyter notebooks (.ipynb). I am trying to do this by emulating this setup (https://www.youtube.com/watch?v=qLvAHhJAVlI). In the repo I have a .devcontainer directory which contains a devcontainer.json and a Dockerfile. However, when I rebuild the codespace, there is no virtual environment to be found. How do I proceed?

Here is the contents of the Dockerfile

ARG VARIANT="3.11" FROM mcr.microsoft.com/vscode/devcontainers/python:${VARIANT}

Define the path to the virtualenv to work with ARG VENV_PATH="/home/vscode/venv"

COPY requirements.txt /tmp/pip-tmp/ RUN su vscode -c "python -m venv /home/vscode/venv"
su vscode -c "${VENV_PATH}/bin/pip --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt"
rm -rf /tmp/pip-tmp

And here is the content of the devcontainer.json:

{ "name": "Python 3", "build": { "dockerfile": "Dockerfile", "context": "..", "args": { "VARIANT": "3.11", Options "NODE_VERSION": "none" } },

"customizations": { "vscode": { "settings": { "python.defaultInterpreterPath": "/home/vscode/venv/bin/python" },

      "extensions": [
          "ms-python.python",
          "ms-python.vscode-pylance",
          "GitHub.copilot"
      ]
  }

},

Use 'postCreateCommand' to run commands after the container is created. // "postCreateCommand": "pip3 install --user -r requirements.txt",

"remoteUser": "vscode", "features": { "azure-cli": "latest" } }

I tried various devcontainer setups using various python interpreter paths. I was expecting for the virtual environment to be initialized and accessed as soon as I opened the terminal.

1 Answer 1

1

Just install your virtual environments to your source code directory, whether you're using venv, poetry, hatch, etc, there should be a configuration option. Then when the dev container mounts your source code, it also mounts the virtual environments. I usually install dependencies in postCreateCommand, which will detect the cache/mount on rebuilds and skip installation.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for this answer! how do you know .venv is automatically detected? is that documented somewhere, or a srtting? i believe you (i took your advice - removed my setting for defaultInterpreterPath and it magically worked) but just wondering if you have any more info that.
The dev container automatically bind mounds all source code in the project folder, which will naturally include .venv

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.