在vscode中选择docker容器的解释器

Hou*_*eYu 22 python docker visual-studio-code

在vscode中,我们可以安装python扩展,然后选择我们想要的解释器,就像conda环境中的python一样。

所以我们可以使用“shift”+“enter”键在终端中逐行运行代码。对于管理不同的虚拟环境,使用docker容器是一个更好的方法。

如果我已经安装了 docker,并拉取 python 映像。如何选择在docker容器中创建的解释器?不仅仅是远程到 docker 容器。

Ali*_*ets 35

在 VSCode 1.61 上测试:

  1. 安装Remote-Containers扩展
  2. 构建/启动 Docker 容器
  3. 打开命令面板并输入Remote-Containers: Attach to Running Container...,然后选择正在运行的 Docker 容器
  4. VSCode 将重新启动并重新加载
  5. Get Started页面上,单击Open...并输入安装到源代码的 Docker 卷的路径。它必须设置为WORKDIR与您的路径相同的路径Dockerfile-local,例如 to /app
  6. Python在容器上安装扩展
  7. 打开命令面板并输入Python: Select Interpreter,然后选择 Docker 解释器
  8. 打开命令面板并输入Python: Configure Tests,然后选择您使用的框架

来源:https ://dev.to/alvarocavalcanti/setting-up-a-python-remote-interpreter-using-docker-1i24

UPD#1。 Remote development extensions似乎是当前 VSCode 开发的主要焦点之一,例如,较新的版本Remote explorer默认启用“活动”选项卡,这允许更直观的方法来连接到 Docker 容器。在此处查看发行说明:https ://github.com/microsoft/vscode-docs/tree/main/remote-release-notes

UPD#2。现在你应该使用开发容器而不是远程容器

请参阅文档: https: //code.visualstudio.com/docs/devcontainers/containers

  1. 创造.devcontainer/devcontainer.json
{
    "name": "My Devcontainer",
    "dockerComposeFile": "docker-compose.yml",
    "service": "app",
    "workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",
    "customizations": {
        ...
Run Code Online (Sandbox Code Playgroud)

文档: https: //containers.dev/implementors/json_reference/

  1. 将您的Dockerfile, docker-compose.yml,添加.env.devcontainers
...
services:
  app:
    build:
      context: ..
      dockerfile: .devcontainer/Dockerfile

    volumes:
      - ../..:/workspaces:cached

    env_file: .env
...
Run Code Online (Sandbox Code Playgroud)
  1. 使用Dev containers: Open folder in containerDev containers: Rebuild container提示继续

  • 似乎步骤 3.、4. 和 5. 得到了简化:https://code.visualstudio.com/docs/devcontainers/attach-container (2认同)

Noa*_*eli 0

devcontainer.jsonvscode 创建的文件中,您有密钥image,其值是图像的路径,如果您想用来更改 python 版本,您可以在那里执行此操作,或者使用此处vscode 文档中的快速说明