Skip to content

Instantly share code, notes, and snippets.

@enven-omiomi
Last active May 17, 2024 04:11
Show Gist options
  • Save enven-omiomi/8aebac5923b8a42ca39ff6ab7876f093 to your computer and use it in GitHub Desktop.
Save enven-omiomi/8aebac5923b8a42ca39ff6ab7876f093 to your computer and use it in GitHub Desktop.
python-invoke

invokeのタスク(task.py)をVSCodeでデバッグしたかったのでやりかたの備忘録

参考: https://zenn.dev/shun_kashiwa/articles/debug-python-cli-with-debugpy-vscode

デバッグ

0. 準備

1. debugpyをインストール

pip install debugpy

2. launch.jsonに構成追加

launch.jsonに以下を追記

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Remote Attach",
      "type": "debugpy",
      "request": "attach",
      "connect": {
        "host": "localhost",
        "port": 5678
      },
    }
  ]
}

3. debugpy起動してinvoke呼び出す

$ python -m debugpy --wait-for-client --listen 5678 -m invoke your-task

--wait-for-clientでVSCodeがattachするのを待ってくれる

4. VSCodeのデバッグを実行

VSCodeの「実行とデバッグ」から前段で作った構成("Python: Remote Attach")を選択してデバッグを開始(F5)すると 3で起動したdebugpyのプロセスにアタッチされる invokeのtask.pyでブレークポイントが設定されていればそこで止まってくれる

改良

まいどCLIでdebugpyを呼び出すのは大変。なので,VSCodeのTaskでdebugpyを起動させ、その後デバッグを自動で実行させる

tasks.json

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
    {
      "label": "pre launch: invoke lint-all",
      "type": "shell",
      "command": "python -m debugpy --wait-for-client --log-to-stderr --listen 5678 -m invoke lint-all",
      "isBackground": true,
      "problemMatcher": {
        "owner": "custom",
        "pattern": {
          "regexp": "^$"
        },
        "background": {
          "activeOnStart": true,
          "beginsPattern": ".*",
          "endsPattern": "wait_for_client()"
        }
      }
    }
  ]
}

--log-to-stderrをつけておくとログ出力をしてくれて、クライアントの呼び出し準備が完了すると末尾に"wait_for_client()"と出力されるのでそれを機にバックグラウンドに移行するようにする

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: Remote Attach",
      "type": "debugpy",
      "request": "attach",
      "connect": {
        "host": "localhost",
        "port": 5678
      },
      "preLaunchTask": "pre launch: invoke lint-all",
    }
  ]
}

preLaunchTaskで作成したタスクを指定する。 これでデバッグ実行するとまずタスクが呼び出されてdebugpy起動した後にデバッグ実行がアタッチしてくれる

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment