2
7

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 5 years have passed since last update.

MacでPythonの開発環境を構築する

Last updated at Posted at 2018-09-02

はじめに

Macには標準でPythonがインストールされていますが、
pyenvを使って複数のバージョン(2系や3系など)のPythonを
簡単に切り替えられるようにするために、
以下の手順に沿って必要なツールをインストールしたいと思います。

Homebrewをインストールする

Homebrew公式サイトからコマンドをコピーし、ターミナルに貼り付けて実行します。

$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Homebrewがインストールできたか確認します。
以下の内容が表示されていれば問題ないでしょう。

$ brew doctor
Your system is ready to brew.

pyenvをインストールする

複数のPython環境に切り替えられるようにpyenvをインストールします。

$ brew install pyenv

.bash_profileという設定ファイルに環境変数やinitコマンドを追加します。
もし.bash_profileが存在しない場合は、先に作成しておきましょう。

$ echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
$ echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(pyenv init -)"' >> ~/.bash_profile

phpenvインストール後に「brew doctor」を実行するとWarningが出る場合、
.bash_profileに以下のコマンドを追加し、
brewコマンドを使う時だけpyenv用のPATHが通らないようにしておきます。

$ echo 'alias brew="env PATH=${PATH/${HOME}\/\.pyenv\/shims:/} brew"' >> ~/.bash_profile

設定を反映させるために、以下のコマンドを実行するか、ターミナルを再起動します。

$ source ~/.bash_profile

Pythonをインストールする

pyenvでインストール可能なPythonのバージョンを確認します。

$ pyenv install --list

利用したいバージョンを選んでインストールします。

$ pyenv install 3.6.5

インストール済みのPythonのバージョンを確認します。
デフォルトではシステム標準のバージョンが選択されている(「*」が付いている)はずです。

$ pyenv versions
* system (set by /Users/[ユーザー名]/.pyenv/version)
  3.6.5

pyenvで利用したいPythonのバージョンを設定します。

$ pyenv global 3.6.5  #システム全体で使いたい場合。
$ pyenv local 3.6.5  #カレントディレクトリだけで使いたい場合。
$ pyenv shell 3.6.5  #一時的に使いたい場合。ターミナルを閉じて再度開いた場合は無効化。
$ pyenv global system  #システム標準の状態に戻す。

再度「pyenv versions」を実行し、「3.6.5」が選択されていれば切り替え成功です。

$ pyenv versions
  system
* 3.6.5 (set by /Users/[ユーザー名]/.pyenv/version)
2
7
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
2
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?