Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a python virtual environment in codespaces using a devcontainer

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.

like image 360
Rudy Brown Avatar asked Feb 22 '26 23:02

Rudy Brown


1 Answers

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.

like image 148
tschlich Avatar answered Feb 24 '26 15:02

tschlich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!