首页 > 解决方案 > 在 VS Code 中调试 Python Docker

问题描述

我的调试器有问题,我无法完全理解。我的问题是:在容器中运行我的代码时,更改不会持续存在。(我已宣布我的卷)

我的设置如下:我创建了一个 python 虚拟环境,然后使用以下内容创建了一个 python 文件(只需将文件写入磁盘)。然后我通过教程使用 docker 命令来添加我所有的 docker 文件。它创建了一个 docker-compose 和一个 docker-compose.debug。我为这两个撰写文件添加了一个卷,以便我的文件将持续存在。如果我执行 docker-compose up 文件将被执行,我看到一个 test.txt 文件到达我的目录。但是,如果我通过调试器运行,它似乎忽略了我的卷声明,然后我的文件不会出现在我的主机目录中。你有什么想法我做错了吗?

https://code.visualstudio.com/docs/containers/quickstart-python

测试.py

import datetime

text_file = open("test.txt", "w")
text_file.write(str(datetime.datetime.now()))
text_file.close()

码头工人-compose.yml

version: '3.4'

services:
  test:
    image: test
    volumes:
      - ${PWD}:/app
    build:
      context: .
      dockerfile: Dockerfile

docker-compose.debug.yml

version: '3.4'

services:
  test:
    image: test
    volumes:
      - ${PWD}:/app
    build:
      context: .
      dockerfile: Dockerfile
    entrypoint: /bin/bash
    command: -c "pip install debugpy -t /tmp && python /tmp/debugpy --wait-for-client --listen 0.0.0.0:5678 test.py"
    ports:
      - 5678:5678

dockerfile

# For more information, please refer to https://aka.ms/vscode-docker-python
FROM python:3.8-slim-buster

# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE 1

# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED 1

# Install pip requirements
ADD requirements.txt .
RUN python -m pip install -r requirements.txt

WORKDIR /app
ADD . /app

# Switching to a non-root user, please refer to https://aka.ms/vscode-docker-python-user-rights
RUN useradd appuser && chown -R appuser /app
USER appuser

# During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug
CMD ["python", "test.py"]

标签: pythondockervisual-studio-codevscode-debugger

解决方案


我发现了一些或多或少会做我想做的事。使用以下作为模板,我创建了一个远程附加配置文件,该配置文件附加到端口 5678 上的任何进程。然后,无论是我的 Web 应用程序还是普通的 python 文件,我在容器上打开端口 5678,添加 pvtsd,然后指示无论我想调试哪个文件来等待附件。似乎工作得很好。

https://code.visualstudio.com/docs/containers/debug-python


推荐阅读