我的主机上运行着一个带有 python 进程的容器,并且我在主机上安装了 VS Code。是否可以从安装了 vscode 的主机调试 python 进程?如果是,如何实现?
由于我不知道你正在运行什么python进程,所以我将使用FastAPI作为示例。
<project_root>/.vscode/launch.json
。要访问此文件,您可以转到活动栏上的运行和调试部分,然后按顶部的齿轮/轮子。在configurations中添加一个新项目,如下所示。
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"connect": {
"host": "localhost",
"port": 5678
},
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "."
}
]
}
]
}
现在您需要包含debugpy。如果您使用需求文件,则只需将其添加到此处即可。如果您使用 Poetry,您可以在终端中运行
poetry add debugpy
(Dockerfile 示例展示了如何在 docker 镜像中使用 Poetry)。
第一个选项 - 在您的Dockerfile中,您需要运行debugpy并使其监听端口5678。 现在,每次运行容器并等待附件时,调试器都会启动。
FROM python:3.10.0
# Set the working directory:
WORKDIR /usr/src
# Copy the pyproject.toml file (or requirements.txt) to cache them in the docker layer:
COPY [ "./src/pyproject.toml", "./"]
# Set the python path if needed.
# For example, if main.py is not located in the project root:
ENV PYTHONPATH="$PYTHONPATH:${PWD}"
# Upgrade pip and install Poetry:
RUN pip install --upgrade pip && pip install poetry==1.1.12
# Project initialization using Poetry:
RUN poetry config virtualenvs.create false \
&& poetry install --no-interaction --no-ansi
# Run the application:
CMD ["python", "-m", "debugpy", "--wait-for-client", "--listen", "0.0.0.0:5678", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload", "--reload-exclude", "tests"]
EXPOSE 8000 5678
debugger = True
if __name__ == "__main__":
if debugger:
import debugpy
debugpy.listen(("0.0.0.0", 5678))
debugpy.wait_for_client()
uvicorn.run(
"main:app",
host="localhost",
port=8000,
log_level="info",
reload=True,
)
Python: Remote Attach
,然后按播放。现在您应该能够在 docker 容器内使用调试器了。
debugpy.listen(("0.0.0.0", 5678)) Traceback (most recent call last): File "/usr/local/lib/python3.8/runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/local/lib/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "/.venv/lib/python3.8/site-packages/debugpy/adapter/__main__.py", line
215,在 导入(“调试”) 文件“/.venv/lib/python3.8/site-packages/debugpy/adapter/../../debugpy/init.py”, 第 35 行,在 from debugpy.public_api import * # noqa 文件“/.venv/lib/python3.8/site-packages/debugpy/adapter/../../debugpy/public_api.py”, 8号线,在 导入打字 文件“/.venv/lib/python3.8/site-packages/debugpy/adapter/../../typing.py”, 第 1359 行,在 Callable 类(额外=collections_abc.Callable,元类=CallableMeta): 文件“/.venv/lib/python3.8/site-packages/debugpy/adapter/../../typing.py”, 第 1007 行,位于new self._abc_registry = extra._abc_registry AttributeError:类型对象“Callable”没有属性“_abc_registry”
使用 debugpy-1.8.1 出现此错误