Help us understand the problem. What is going on with this article?

VSCode で Python コンテナ内で実行したコードをデバッグする

目次

  • 環境
  • Docker でデバッグ用の Python コンテナ作成
  • サンプルコード
  • デバッグ

環境

macOS Mojave
Docker version 19.03.2, build 6a30dfc

コンテナ作成

デバッグ(開発)用に使う Python のコンテナイメージを作成する

Dockerfile

Dockerfile
FROM python:3
WORKDIR /app
RUN pip install -U pip \
    && pip install ptvsd

イメージ作成

docker build -t python-debug .

コンテナ起動

docker run -it -d --name=python-debug -v /path/to/app:/app -p 5678:5678 python-debug

デバッグ

VSCode のデバッグ設定を行う
⌘⇧P で launch.json を開き以下を入力

launch.json
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Attach",
            "type": "python",
            "request": "attach",
            "port": 5678,
            "host": "localhost",            
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}", 
                    "remoteRoot": "/app"
                }
            ],
        }
    ]
}

サンプルコード

hello.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

def main():
    msg = "hello world"
    print(msg)

if __name__ == '__main__':
    if (len(sys.argv) > 1) and (sys.argv[1] == "debug"):
        import ptvsd
        print("waiting...")
        ptvsd.enable_attach(address=('0.0.0.0', 5678))
        ptvsd.wait_for_attach()
    main()

ここまできたら、デバッグの準備は終了

docker exec -it -d python-debug /bin/bash

でコンテナ内に入り、 python hello.py debug を実行し、 waiting... と表示されたら、
VSCode で適当にブレークポイントを張り、実行するとキャッチできるはず

参考:
Python Remote Debug
VSCodeでPythonのリモートデバッグ


余談

個人的には、Python の開発は VSCode よりも PyCharm の方がやりやすいから、コーディングは PyCharm でして、デバッグは VSCode で行うスタイルがやりやすいです。

VS Code Remote Development で立ち上げたコンテナに接続してもデバッグできないよね...??
それでできる方法あれば参考リンクなど教えてください m(_ _)m

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした