0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

VSCodeでStart Debuggingで実行したときにデバッグ処理を行う

Last updated at Posted at 2024-10-23

概要

  • VSCodeでPythonの開発をしており、Run > Start Debuggingで実行したときのみ、デバッグ処理としてコマンドライン引数を渡しながらスクリプトの動作を確認したい

参考

実装

  • .vscode/launch.jsonにenvを追加し、そこにデバッグ時にのみ有効になる環境変数を追加する
.vscode/launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python Debugger: Current File",
            "type": "debugpy",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
+            "env": {
+                "VSCODE_DEBUG_MODE": "true"
+            }
        }
    ]
}
  • config.pyを作成しenvの情報を取得する処理を書く
config.py
import os

# VSCodeからデバッグモードで起動しているかどうか
VSCODE_DEBUG_MODE = bool(os.environ.get("VSCODE_DEBUG_MODE"))
  • 呼び出し例は以下の通り
  • デバッグ起動時に自動でコマンドライン引数を渡せるようにしている
import sys

from src.utils.config import VSCODE_DEBUG_MODE


def main() -> None:
    if VSCODE_DEBUG_MODE:
        sys.argv += ["-m", "Hello, Python"]
    print(sys.argv)


if __name__ == "__main__":
    main()
  • 実行結果は以下の通り
# Run > Start Debuggingから実行した場合
['<path-to-dir>/src/api/hoge.py', '-m', 'Hello, Python']

# uv run hoge.pyを直接実行した場合
['<path-to-dir>/src/api/hoge.py']
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?