0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python環境構築[Mac(M1)]

Last updated at Posted at 2022-06-01

目次

  1. Xcodeインストール
  2. brewインストール
  3. pyenvインストール
  4. Pythonインストール
  5. Visual Studio Codeインストール
  6. Visual Studio Code設定
  7. 仮想環境構築
  8. 仮想環境運用

1. Xcodeインストトール

XcodeはM1Macで開発環境を構築するものです。

AppStoreより、Xcodeアプリをインストールします。

2. brewインストール

brewはmac用のパッケージインストーラーです。

以下より、Install HomebrewのURLをコピーして、ターミナルで実行します。

3. pyenvインストール

pyenvとは、pythonのバージョンを管理するものです。

ターミナルで以下を実行します。

export PATH=/opt/homebrew/bin:$PATH    # パス追加
brew install pyenv    # pyenvインストール

4. Pythonインストール

ターミナルで以下を実行します。

pyenv install -l    # インストール可能なリストを表示
pyenv install _Number_    # 上記のリストの上の方を確認して、好きなバージョンを選択

5. Visual Studio Codeインストール

下記のサイトより、インストールできます。

6. Visual Studio Code設定

vscodeの拡張機能より、Pythonをインストールします。

7. 仮想環境構築

パッケージをインストールして、vscodeに反映させます。

vscodeで任意のフォルダーを開き、フォルダ内に以下のファイルを作成します。

.zshrc
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv init -)"

ターミナルで以下を実行します。

pyenv local _Number_   # pythonのパスを追加
python -m venv .venv   # .venvという名前の仮想環境を作成
. .venv/bin/activate    # 仮想環境(.venv)に切り替え

先頭に(.venv)と表示された状態で以下を実行すると仮想環境にパッケージがインストールできます。

# which pipで有効化されているpipのパスが取得できます。
pip install <package>    # <パッケージ名>

Pythonのインタープリター選択で.venvを選択し、vscodeで仮想環境(.venv)を認識させます。

8. 仮想環境運用

インストールしたパッケージを管理します。

pip freeze > requirements.txt    # requirements.txtに出力
pip install -r requirements.txt    # requirements.txtよりインストール

ファイルでもできる?
フォルダーに.vscode/setting.jsonができれば完了です。
Ctrl+Shift+Pで検索画面を表示させて、[setting]と検索して、Open Workspace Settings (JSON)を開きます。以下を追加してください。パスは相対パスで構いません。

settings.json
{
   "python.defaultInterpreterPath": ".venv/Scripts/python.exe"
}
0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?