chai
chai

Reputation: 510

How to setup vscode autocomplete for Python modules installed only in a container?

I am building a Python application with the Pygame library and I am using Docker to containerize it.

Here is the Dockerfile:

FROM python

WORKDIR /app

COPY requirements.txt .

RUN pip install -r requirements.txt

COPY . .

CMD ["python", "main.py"]

Here is requirements.txt:

autopep8==1.6.0
pygame==2.1.0

Here is the docker-compose.yaml file:

version: "3.8"
services:
  app:
    build: ./
    stdin_open: true
    tty: true

Here is main.py:

import pygame

print("hello there")

This is what happens when I run docker-compose up:

Attaching to connect-four_app_1
app_1  | pygame 2.1.0 (SDL 2.0.16, Python 3.10.1)
app_1  | Hello from the pygame community. https://www.pygame.org/contribute.html
app_1  | hello there
connect-four_app_1 exited with code 0

As you can see, the application is working perfectly fine. The only problem is that in my main.py file, VSCode isn't able to find pygame, i.e. it thinks it isn't installed, and therefore I don't get any autocompletion for the library. How do I tell VSCode that pygame is in fact installed, but only in the container?

Thanks a bunch.

Upvotes: 1

Views: 217

Answers (2)

Izydorr
Izydorr

Reputation: 2001

I believe VSCode Dev Containers extension is the answer to your needs. You'll find full documentation here: https://code.visualstudio.com/docs/devcontainers/containers

The quick action is to install Docker and Dev Containers extensions in your VSCode, then after starting the containers you can simply connect to the one you want to work in by "Dev Containers: Attach to Running Container..." or by right clicking on the container in Docker extension panel and choosing "Attach Visual Code Studio".

Once you're connected you have to install needed extensions (Python, ...) in the container (using VSCode GUI) but VSCode saves your configuration and whey you run the container again it will restore the extensions (no changes in Dockerfile are required). Open folder with your WORKSPACE and the autocompletion works.

Upvotes: 1

Paulino Veloso
Paulino Veloso

Reputation: 9

I have never worked with Docker so I do not know if this will help you. But my experience working with virtualenvs is that you should tell VS Code what Python interpreter you want it to use to run your code. Depending on where you have installed the packages, maybe you are using an interpreter that cannot reach the packages you have installed (maybe you have this package using a different Python installation, on a different directory).

Just to rule out that this is not the problem, try pressing F1 and then typing/selecting "Python: Select interpreter" on VS Code. And then you can go through all Python versions installed in your PC to see which one recognizes the packages you want. Hope this help you a bit.

Upvotes: 0

Related Questions