Visual Studio CodeでのPython開発環境構築の手順を記載していきます。
Pythonをインストールします。
# Raspberry Pi Zero WHがpython 3.9なのでそれに合わせます。 brew install python@3.9 python3.9 -V → Python 3.9.16
Visual Studio Codeをインストールします。
taogya.hatenablog.com
日本語化します。
taogya.hatenablog.com
以下、拡張機能をインストールします。
- isort
- Python (最初から入ってる?)
- autopep8
- Flake8
- Remote Development
- ShellCheck
- autoDocstring - Python Docstring Generator
- indent-rainbow
作業ディレクトリを作成します。
mkdir -p ~/develop/python/demo cd ~/develop/python/demo
仮想環境作成を作成します。
python3.9 -m venv venv
Visual Studio Codeで作業ディレクトリを開きます。
警告出るので、以下の通り選択します。
- 親フォルダー 'python' 内のすべてのファイルの作成者を信頼します。 → チェック
- はい、作成者を信頼します。 → 選択
srcフォルダを作成します。この下に実行ファイルを格納していきます。
~/develop/python/demo └ src └ hello.py → print('hello world.')
isortのコンフィグファイル.isort.cfg*1を作成します。
~/develop/python/demo ├ src │ └ hello.py └ .isort.cfg → [settings] default_section=THIRDPARTY force_single_line=False known_first_party= sections = FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER
.vscodeフォルダを作成します。
~/develop/python/demo ├ .vscode ├ src │ └ hello.py └ .isort.cfg
.vscode配下に設定ファイルsettings.json*2を作成します。
~/develop/python/demo ├ .vscode │ └ settings.json ├ src │ └ hello.py └ .isort.cfg →{ "python.defaultInterpreterPath": "${workspaceFolder}/venv/bin/python3.9", "python.analysis.extraPaths": [ "${workspaceFolder}/src" ], "python.linting.enabled": true, // Lint機能を有効にするかどうか "python.linting.pylintEnabled": false, // Linterにpylintを使用するかどうか "python.linting.lintOnSave": true, // ファイル保存時にLintを実行するか "editor.formatOnSave": true, // ファイル保存時にフォーマットをかけるか // flake8 "python.linting.flake8Enabled": true, "python.linting.flake8Args": [ "--ignore=E501, W503, W504", ], // Pythonコードの整形にautopep8を指定 "python.formatting.provider": "autopep8", "python.formatting.autopep8Args": [ "--ignore=E501, W503, W504", ], // isort "[python]": { "editor.codeActionsOnSave": { "source.organizeImports": true }, }, "isort.check": true, "isort.args": [ "--settings-file", "${workspaceFolder}/.isort.cfg", ], }// [2024/01/21] 上記設定値は古くなったよう。新しい設定値は以下。 { "python.defaultInterpreterPath": "${workspaceFolder}/venv/bin/python3.9", "python.analysis.extraPaths": [ "${workspaceFolder}/src" ], "editor.formatOnSave": true, // ファイル保存時にフォーマットをかけるか // flake8 "flake8.args": [ "--ignore=E501, W503, W504", ], // autopep8 "autopep8.args": [ "--ignore=E501, W503, W504", ], // isort "[python]": { "editor.codeActionsOnSave": { "source.organizeImports": "explicit" }, "editor.defaultFormatter": "ms-python.autopep8", }, "isort.check": true, "isort.args": [ "--settings-file", "${workspaceFolder}/.isort.cfg", ], }
.vscode配下に実行設定ファイルlaunch.json*3を作成します。
~/develop/python/demo ├ .vscode │ ├ settings.json │ └ launch.json ├ src │ └ hello.py └ .isort.cfg → { "version": "0.2.0", "configurations": [ { "name": "HelloWorld", "type": "python", "request": "launch", "program": "${workspaceFolder}/src/hello.py", "args": [], // "django": true, }, ] }
実行とデバッグを選択し、実行する設定を選択。
再生マークを押すと、実行できる。