LoginSignup
3
2

More than 3 years have passed since last update.

Python 環境構築(Mac)

Posted at

2019.09.08 作成。

『直感 Deep Learning』のリポジトリで環境構築しようとしたが上手くいかなかったのでメモ。

結果から言うとかなり面倒だった。

予備知識

Mac 使用、homebrew 使用。

  • pyenv : python のバージョンを自由に切り替える
  • pyenv-virtualenv : python の仮想環境を構築する

Python はバージョン2と3で使い分ける事が多いので、環境の切り替えが重要らしい。

インストール

まずは pyenv, pyenv-virtualenv(そして python)をインストールする。

$ brew install pyenv
$ brew install pyenv-virtualenv
$ pyenv install 3.6.0
$ pyenv rehash
$ pyenv local 3.6.0

local のバージョンを設定すると、.python-version という設定ファイルが生成される。

ただ、pyenv をインストールしただけでは使えるようにならない。PATH を通す必要がある。

また、pyenv-virtualenv をインストールすると、

To enable auto-activation add to your profile:
  if which pyenv-virtualenv-init > /dev/null; then eval "$(pyenv virtualenv-init -)"; fi

と言われる。これは仮想環境の起動を簡略化できる記述らしい。(本来、virtualenv では仮想環境の起動に $ pyenv activate が必要とのこと。)

というわけで、~/.bash_profile を更新する。

.bash_profile

# pyenv の設定
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"

# pyenv の auto-activation を有効化する
if which pyenv-virtualenv-init > /dev/null; then eval "$(pyenv virtualenv-init -)"; fi

.bash_profile を更新したら、適用もしておく。

$ source ~/.bash_profile

仮想環境の構築

準備ができたので、python の仮想環境を構築する。コマンドは $ pyenv virtualenv {バージョン} {環境名}

$ pyenv virtualenv 3.6.0 env_python3.6
Requirement already satisfied: setuptools in /Users/xxx/.pyenv/versions/3.6.0/envs/python3.6/lib/python3.6/site-packages
Requirement already satisfied: pip in /Users/xxx/.pyenv/versions/3.6.0/envs/python3.6/lib/python3.6/site-packages

作られた環境は、バージョン一覧で確認できる。

$ pyenv versions
  system
* 3.6.0 (set by /Users/xxx/git/deep-learning-with-keras-ja/.python-version)
  3.6.0/envs/python3.6
  python3.6

一覧を見ると、pyenv でインストールしたバージョンと、virtualenvで構築した環境(python3.6)が並んでいる。

最後、カレントディレクトリで構築した環境(python3.6)を使用するように設定。

$ pyenv local python3.6
(python3.6) ~/git/deep-learning-with-keras-ja (master)
$ python -V
Python 3.6.0
$ pip -V
pip 9.0.1 from /Users/xxx/.pyenv/versions/3.6.0/envs/python3.6/lib/python3.6/site-packages (python 3.6)

先頭に仮想環境の名前が表示されるようになった。

他のディレクトリでは元の Python 2.7.10 が使われている。

(python3.6) ~/git/deep-learning-with-keras-ja (master)
> cd ..
~/git
> python -V
Python 2.7.10

local だけでなく grobal 設定もあるようだが、今は必要ないので環境構築は一旦これで完了。

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