invokeのタスク(task.py
)をVSCodeでデバッグしたかったのでやりかたの備忘録
参考: https://zenn.dev/shun_kashiwa/articles/debug-python-cli-with-debugpy-vscode
- VSCodeでPython Debugger拡張入れておく
- python拡張を入れるとPylanceと一緒に自動でインストールされる
pip install debugpy
launch.json
に以下を追記
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Remote Attach",
"type": "debugpy",
"request": "attach",
"connect": {
"host": "localhost",
"port": 5678
},
}
]
}
$ python -m debugpy --wait-for-client --listen 5678 -m invoke your-task
--wait-for-client
でVSCodeがattachするのを待ってくれる
VSCodeの「実行とデバッグ」から前段で作った構成("Python: Remote Attach")を選択してデバッグを開始(F5)すると 3で起動したdebugpyのプロセスにアタッチされる invokeのtask.pyでブレークポイントが設定されていればそこで止まってくれる
まいどCLIでdebugpyを呼び出すのは大変。なので,VSCodeのTaskでdebugpyを起動させ、その後デバッグを自動で実行させる
{
// 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()"と出力されるのでそれを機にバックグラウンドに移行するようにする
{
// 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起動した後にデバッグ実行がアタッチしてくれる