LoginSignup
2
4

M1 MacBook ProでPythonとVisualStudioCodeの環境設定

Last updated at Posted at 2021-12-13

追記(2023-11-13)

  • pyenvpoetryを使う形に乗り換えた。
  • またLinterなども拡張機能で利用する形にしている
    • Black Formatter: blackを用いたフォーマッター
    • Flake8: flake8にそったlinter
    • isort: import順のチェック
    • Mypy Type Cheker: 型チェック
  • .vscode/settings.jsonは以下の通り
{
    "[python]": {
        // VS Code のフォーマッターは無効にしておく
        "editor.defaultFormatter": "ms-python.black-formatter",
        "editor.formatOnSave": true,
        "editor.codeActionsOnSave": {
            "source.organizeImports": true
        },
    },
    "isort.args":["--profile", "black"],
    "flake8.args": [
        "--max-line-length=79",
        "--max-complexity=10",
    ],
    "mypy-type-checker.args": [
        "--ignore-missing-imports",
        "--disallow-untyped-defs",
        // "--config-file=<file>"
    ],
    // flake8と最大文字数を合わせる
    "black-formatter.args": [
        "--line-length=79",
    ]
}

概要

  • MacBook Pro(14インチ、2021)を購入した。
  • このMacにPythonとVisualStudioCodeの設定したときの忘備録

Homebrew

概要

pyenvpyenv-virtualenvをHomebrewで管理するので先にこれをインストールする

インストール

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

環境設定

Warning: /opt/homebrew/bin is not in your PATH.
  Instructions on how to configure your shell for Homebrew
  can be found in the 'Next steps' section below.
==> Installation successful!

==> Homebrew has enabled anonymous aggregate formulae and cask analytics.
Read the analytics documentation (and how to opt-out) here:
  https://docs.brew.sh/Analytics
No analytics data has been sent yet (nor will any be during this install run).

==> Homebrew is run entirely by unpaid volunteers. Please consider donating:
  https://github.com/Homebrew/brew#donations

==> Next steps:
- Run these two commands in your terminal to add Homebrew to your PATH:
    echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> /Users/ikeh/.zprofile
    eval "$(/opt/homebrew/bin/brew shellenv)"
- Run brew help to get started
- Further documentation:
    https://docs.brew.sh
  • .zprofileに下記のように保存される
image
  • 下記でパスが通っていることの確認
brew -v
Homebrew 3.3.7
Homebrew/homebrew-core (git revision 1d0c0a20808; last commit 2021-12-12)

Python

pyenv/pyenv-virtualenvのインストール

$ brew update
$ brew install pyenv
$ brew install pyenv-virtualenv
# pyenv
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init --path)"

# pyenv-vertualenv
eval "$(pyenv virtualenv-init -)"
  • .zshrc
# pyenv
eval "$(pyenv init -)"
  • 運用時によく使うコマンド
pyenv install --list
pyenv install <python-version>
pyenv versions
pyenv virtualenv <python-version> <env-name>
pyenv local <python-version>
pyenv uninstall projectA

キャッシュファイルを作らない設定

export PYTHONDONTWRITEBYTECODE=1

.gitignoreの設定

brew install gibo
gibo update

// 現在のパス直下に`.gitignore`が出力される
gibo dump python VisualStudioCode > .gitignore

Visual Studio Code

ダウンロード

Extensions

  • 下記が画像表示ができて便利
image

pipでパッケージのインストール

flake8とautopep8

  • flake8autopep8のインストールを行います
    • flake8: PEP8のルールに沿っていない場合に警告してくれるやつ
    • autopep8: Format Selectionとかで自動整形してくれるやつ
image
pip install flake8 
pip install autopep8

PyAutoGUI

  • pyautogui以外にもインストールしておかないと動かないので注意
pip install pyautogui
pip install pillow
pip install opencv-contrib-python

設定ファイル

image image
  • 尚プロジェクトでのみの設定をしたい場合は下記のディレクトリ・ファイルを作成し開きます
<プロジェクトディレクトリ>
├ .vscode
│    └ settings.json
│
{
    // Ref: [VS Code コーディング規約を快適に守る](https://qiita.com/firedfly/items/00c34018581c6cec9b84)

    ////////////
    // flake8  /
    ////////////

    // 一般設定
    "python.linting.pylintEnabled": false,  // 標準のpylintをOFF
    "python.linting.flake8Enabled": true,  // PEP8をON
    
    // 1秒ごとに自動保存して、その度に構文チェック。
    "files.autoSave": "afterDelay",
    "files.autoSaveDelay": 1000,
    "python.linting.lintOnSave": true,

    // 一部ルールの無効化
    "python.linting.flake8Args": [
        // W293: 空行に空白が含まれるとWarningになるW293は、エディタの自動インデントが引っかかるのでオフ。
        // W504: +などのオペレータの後で改行するとWarningになる
        // E501: 一行の文字数が多すぎるかどうか。ワンライナーのほうが見やすい箇所があるのでオフ。
        "--ignore=W293, W504, E501",
        // "--max-line-length=150",  // 1行の最大文字数はデフォルト80文字(PEP8準拠)
        "--max-complexity=20",  // 循環的複雑度
    ],

    /////////////
    // autopep8 /
    /////////////
    "python.formatting.provider": "autopep8",
    
    // より積極的なフォーマッティングを行う。e.g. a == None を a is None に書き換える
    "python.formatting.autopep8Args": [
        "--aggressive", "--aggressive",  // aggressiveレベル2
    ],
}

デバッグ実行時に引数を設定

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "args" : [
                "(引数1)",
                "(引数2)",
            ]
        }
    ]
}
2
4
1

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
2
4