LoginSignup
29
35

More than 5 years have passed since last update.

pythonの環境構築【pyenvとpyenv-virtualenv】

Last updated at Posted at 2017-12-17

今回は前回の記事に引き続き、pythonの開発環境の構築を行なっていきたいと思います!

環境を構築

今回の記事ではpythonの開発環境を構築する上で、pythonのバージョン管理ツールとしてpyenvをインストールして、仮想環境の管理をpyenv-virtualenvをインストールします。

今回インストールするもの

  • pyenv
  • pyenv-virtualenv
  • python

上記のパッケージをインストールしてより開発しやすい環境にする!
バージョン管理と仮想環境構築するためのそれぞれのパッケージの選び方は、こちらの記事が参考になりました。パッケージの組み合わせについても書かれているので、読んでみるといいかもしれないです!
- Pythonの仮想環境構築(2017年版) pyenvとpyenv-virtualenvとvirtualenvとvirtualenvwrapperとpyvenvとvenv

前提条件

  • Homebrew インストール済み

本記事では、Homebrewを使って環境構築を行なっていきます。なのでこれはあらかじめインストールを済ませておいてください。

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

pyenvのインストール

まずはpyenvからインストールをしていきます。そのためにまずは現在の状況確認ですね!

bash
$ brew list
autoconf    gdbm        libpng      pkg-config  sqlite      zsh
coreutils   heroku      openssl     postgresql  tree
freetype    heroku-node pcre        readline    xz

これで現在インストールされているパッケージ一覧が表示できました。pyenvは入っていないようなのでインストールしていきます。

bash
$ brew install pyenv
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 4 taps (heroku/brew, homebrew/core, caskroom/fonts, caskroom/cask).
==> New Formulae
apm-server              dislocker               envconsul               kubeless                raylib
avimetaedit             dnsdist                 glslviewer              libxo                   restic
bedtools                docker-ls               heartbeat               logstash@5.6            sceptre
chamber                 dps8m                   joplin                  mrboom                  simg2img
cling                   e2tools                 kaitai-struct-compiler  neal                    vert
clingo                  elasticsearch@5.6       kibana@5.6              ocaml-findlib
==> Updated Formulae
heroku ✔                      geoserver                     logtalk                       qd
heroku/brew/heroku ✔          get_iplayer                   lsyncd                        qscintilla2
heroku/brew/heroku-node ✔     getdns                        lua                           qt
openssl ✔                     geth                          lua@5.1                       qtfaststart
postgresql ✔                  ghc                           lutok                         r
abcm2ps                       git                           lxc                           radare2


...省略...


This formula is keg-only, which means it was not symlinked into /usr/local,
because Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries.

If you need to have this software first in your PATH run:
  echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile

For compilers to find this software you may need to set:
    LDFLAGS:  -L/usr/local/opt/openssl/lib
    CPPFLAGS: -I/usr/local/opt/openssl/include
For pkg-config to find this software you may need to set:
    PKG_CONFIG_PATH: /usr/local/opt/openssl/lib/pkgconfig

==> Summary
🍺  /usr/local/Cellar/openssl/1.0.2n: 1,792 files, 12.3MB
==> Installing pyenv
==> Downloading https://homebrew.bintray.com/bottles/pyenv-1.1.5.high_sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring pyenv-1.1.5.high_sierra.bottle.tar.gz
🍺  /usr/local/Cellar/pyenv/1.1.5: 594 files, 2.3MB

このようにエラーが出ていなければpyenvのインストールは終了です。

bash
$ brew list
autoconf    gdbm        libpng      pkg-config  readline    xz
coreutils   heroku      openssl     postgresql  sqlite      zsh
freetype    heroku-node pcre        pyenv       tree

パッケージの一覧を確認すると、ちゃんと入っていることが確認できます!

続いてシェルスクリプトを記述していきます。

bash
$ vi ~/.bash_profile
vim
if which pyenv > /dev/null; then eval "$(pyenv init -)"    ; fi

ではpyenvを動かしてみましょう!

bash
$ pyenv --version
pyenv 1.1.5

これでバージョンが表示されていれば正常にインストールできています!
もしエラーが出た場合はシェルスクリプトの設定に誤りがあるか、インストールが正常に完了していない可能性があります。

pyenv-virtualenvのインストール

引き続きpyenv-virtualenvをインストールしていきます。

bash
$ brew install pyenv-virtualenv
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 2 taps (homebrew/core, caskroom/cask).
==> New Formulae
node@8
==> Updated Formulae
abcmidi                       jruby
ace                           kibana@5.6
binaryen                      kontena
carthage                      kubernetes-cli
ceres-solver                  liblinear
clojure                       libmicrohttpd
docfx                         libqalculate
elasticsearch                 logstash
elasticsearch@5.6             logstash@5.6
fibjs                         metricbeat
filebeat                      mockserver
flow                          mrboom
fn                            node
folly                         node-build
game-music-emu                node@4
gjstest                       node@6
glog                          osquery
gradle                        packetbeat
gsoap                         peco
gst-editing-services          percona-server@5.5
gst-libav                     percona-server@5.6
gst-plugins-bad               planck
gst-plugins-base              presto
gst-plugins-good              pulledpork
gst-plugins-ugly              rustup-init
gst-python                    securefs
gst-rtsp-server               swiftformat
gst-validate                  tarantool
gstreamer                     telegraf
heartbeat                     thrift
heimdal                       tmuxinator-completion
jhipster                      vips
joplin

==> Downloading https://github.com/pyenv/pyenv-virtualenv/a
==> Downloading from https://codeload.github.com/pyenv/pyen
############################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################## 100.0%
==> ./install.sh
==> Caveats
To enable auto-activation add to your profile:
  if which pyenv-virtualenv-init > /dev/null; then eval "$(pyenv virtualenv-init -)"; fi
==> Summary
🍺  /usr/local/Cellar/pyenv-virtualenv/1.1.1: 20 files, 60.6KB, built in 3 seconds

先ほどと同様シェルスクリプトを記述していきます。

bash
$ vi ~/.bash_profile
vim
if which pyenv-virtualenv-init > /dev/null; then eval "$(pyenv virtualenv-init -)"; fi

これで一通りのインストールは終了です!

使用方法

pyenvでpythonのインストール

まずはpyenvを使ってpythonをインストールしてみます。インストール可能なpythonの種類はリストとして見ることができます。

bash
$ pyenv install --list
Available versions:
  2.1.3
  2.2.3
  2.3.7
  2.4

...省略... 

  2.7.12
  2.7.13
  2.7.14
  3.0.1
  3.1
  3.1.1
  3.1.2
  3.1.3
  3.1.4

...省略...

  3.6.0
  3.6-dev
  3.6.1
  3.6.2
  3.6.3
  3.7.0a1
  3.7-dev
  anaconda-1.4.0
  anaconda-1.5.0
  anaconda-1.5.1
  anaconda-1.6.0
  anaconda-1.6.1

...省略...

   stackless-3.2.5
  stackless-3.3-dev
  stackless-3.3.5
  stackless-3.4.1
  stackless-3.4.2

さずがに量が多いのでlistの一覧は部分的に省略しましたが、こんな感じで表示されていると思います。これはインストールされているpythonの一覧ではないので注意してください。このリストアップされたものの中から、インストールしたいpythonのバージョンを選択します。

今回は2系と3系をインストールしてみたい思います。
先ほどのリストを見ると2系は2.7.14、3系は3.6.3が新しそうなのでこの二つをインストールしてみましょう。

↓今はエラーが出ないようなのでエラーが出ない場合は飛ばしてもらって大丈夫です!

bash
$ pyenv install 2.7.14
Downloading Python-2.7.14.tar.xz...
-> https://www.python.org/ftp/python/2.7.14/Python-2.7.14.tar.xz
Installing Python-2.7.14...
ERROR: The Python ssl extension was not compiled. Missing the OpenSSL lib?

Please consult to the Wiki page to fix the problem.
https://github.com/pyenv/pyenv/wiki/Common-build-problems


BUILD FAILED (OS X 10.13.2 using python-build 20160602)

Inspect or clean up the working tree at >/var/folders/hd/vj79scgn2zzd4gf2lq36mth40000gn/T/python-build.20171209101010.6988
Results logged to /var/folders/hd/vj79scgn2zzd4gf2lq36mth40000gn/T/python->build.20171209101010.6988.log

Last 10 log lines:
rm -f /Users/user/.pyenv/versions/2.7.14/share/man/man1/python.1
(cd /Users/user/.pyenv/versions/2.7.14/share/man/man1; ln -s python2.1 python.1)
if test "xno" != "xno"  ; then \
      case no in \
          upgrade) ensurepip="--upgrade" ;; \
          install|*) ensurepip="" ;; \
      esac; \
       ./python.exe -E -m ensurepip \
          $ensurepip --root=/ ; \
  fi

あら...なんかエラーが出てる...
とりあえずhttps://github.com/pyenv/pyenv/wiki/Common-build-problemsを見ろって書いてあるので飛んでみましょう。すると以下のような内容の記事がありました。

gitページ

まぁつまり、これを打ち込めということですね。

bash
$ CFLAGS="-I$(brew --prefix openssl)/include" \LDFLAGS="-L$(brew --prefix >openssl)/lib" \pyenv install -v 3.4.3

...省略...

Successfully installed pip-6.0.8 setuptools-12.0.5
/var/folders/hd/vj79scgn2zzd4gf2lq36mth40000gn/T/python-build.20171209113944.17113 ~/workspace
~/workspace
Installed Python-3.4.3 to /Users/user/.pyenv/versions/3.4.3

おそらく成功したでしょう。とりあえずpyenvでインストールされているものの一覧を表示してみます。

bash
$ pyenv versions
* system (set by /Users/user/.pyenv/version)
  3.4.3

なんか3.4.3が入ってますね。まぁそれはいいとして、問題は2.7.14をインストールしたいってことですね。
もう一度チャレンジしてみます。

bash
$ pyenv install 2.7.14
Downloading Python-2.7.14.tar.xz...
-> https://www.python.org/ftp/python/2.7.14/Python-2.7.14.tar.xz
Installing Python-2.7.14...
ERROR: The Python ssl extension was not compiled. Missing the OpenSSL lib?

Please consult to the Wiki page to fix the problem.
https://github.com/pyenv/pyenv/wiki/Common-build-problems


BUILD FAILED (OS X 10.13.2 using python-build 20160602)

Inspect or clean up the working tree at /var/folders/hd/vj79scgn2zzd4gf2lq36mth40000gn/T/python-build.20171209114542.28207
Results logged to /var/folders/hd/vj79scgn2zzd4gf2lq36mth40000gn/T/python-build.20171209114542.28207.log

...省略...

無理じゃん...
調べたところいい記事があったのでそれを参考に進めてみます。
- High Sierra(macOS 10.13)でpyenvがエラーになった時に対処した方法

bash
$ brew install readline openssl xz
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 2 taps (homebrew/core, caskroom/cask).
==> Updated Formulae
mpv

Warning: readline 7.0.3_1 is already installed
Warning: openssl 1.0.2n is already installed
Warning: xz 5.2.3 is already installed

私はこの3つのパッケージに関してはインストール済みだったみたいですね。インストールしてなかった人は違う結果が返ってきていると思います。

続いてenv-exporterを作って記述していきます!

bash
$ vi ~/.env-exporter
vim
  1 # about zlib
  2 export CFLAGS="-I$(xcrun --show-sdk-path)/usr/include"
  3 # about readline
  4 export CFLAGS="-I$(brew --prefix readline)/include $CFLAGS"
  5 export LDFLAGS="-L$(brew --prefix readline)/lib $LDFLAGS"
  6 # about openssl
  7 export CFLAGS="-I$(brew --prefix openssl)/include $CFLAGS"
  8 export LDFLAGS="-L$(brew --prefix openssl)/lib $LDFLAGS"
  9 # about SQLite (maybe not necessary)
 10 export CFLAGS="-I$(brew --prefix sqlite)/include $CFLAGS"
 11 export LDFLAGS="-L$(brew --prefix sqlite)/lib $LDFLAGS"
bash
$ source ~/.env-exporter

一通り終わったので今度こそいけるはず!

bash
$ pyenv install 2.7.14
Downloading Python-2.7.14.tar.xz...
-> https://www.python.org/ftp/python/2.7.14/Python-2.7.14.tar.xz
Installing Python-2.7.14...
Installed Python-2.7.14 to /Users/user/.pyenv/versions/2.7.14

やっとできた...

bash
$ pyenv versions
* system (set by /Users/user/.pyenv/version)
  2.7.14
  3.4.3

きたぁぁぁ!キタ(・ω・)コレ!
これでやっと2.7.14のインストールはできました。では3.6.3もインストールしてみます。

bash
$ pyenv install 3.6.3
Downloading Python-3.6.3.tar.xz...
-> https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz
Installing Python-3.6.3...
Installed Python-3.6.3 to /Users/user/.pyenv/versions/3.6.3

$ pyenv versions
* system (set by /Users/user/.pyenv/version)
  2.7.14
  3.4.3
  3.6.3

これでpythonのインストールは完了しました!!

pyenvの使用例

pyenvpythonのバージョンを管理するためのパッケージです。簡単に説明すると、これを使うことで今いるディレクトリに適用されるpythonのバージョンを簡単に変更することができます。

bash
$ mkdir sample

$ cd sample

$ python -V
Python 2.7.10

今、新しくsampleという名前でディレクトリを作成し、作成したディレクトリに移動した後で現在適用されているpythonのバージョンを確認するとpythonのバージョンは2.7.10になっていました。これはMacに入っているpythonのバージョンが適応されています。

bash
$ pyenv local 2.7.14

$ python -V
Python 2.7.14

$ cd ..

$ python -V
Python 2.7.10

1行目で今いるディレクトリのpythonのバージョンをpyenvにインストールした2.7.14に変更しました。その後1つ上のディレクトリに移動し再度pythonのバージョンを確認しても2.7.10のままです。このようにディレクトリごとにpythonのバージョンを管理できます。

pyenv-virtualenvで仮想環境を構築

続いてpyenv-virtualenvを使って仮想環境の構築をしていきます。

bash
$ pyenv virtualenv 3.6.3 test3.6.3
Requirement already satisfied: setuptools in /Users/user/.pyenv/versions/3.6.3/envs/test3.6.3/lib/python3.6/site-packages
Requirement already satisfied: pip in /Users/user/.pyenv/versions/3.6.3/envs/test3.6.3/lib/python3.6/site-packages

$ pyenv versions
* system (set by /Users/user/.pyenv/version)
  2.7.14
  3.4.3
  3.6.3
  3.6.3/envs/test3.6.3
  test3.6.3

これで仮想環境の構築は完了です。

では先ほど作ったディレクトリに仮想環境を適応してみます。

bash
$ pyenv local test3.6.3

(test3.6.3) $ python -V
Python 3.6.3

(test3.6.3) $ cd ..

$ python -V
Python 2.7.10

仮想環境が適応されると(仮想環境の名前)が表示されるようになります。
先ほどと同様にディレクトリを移動すると、適応されているpythonのバージョンが変化していることがわかります。

これで一連の環境構築は終了です!!!お疲れ様でした!\\\٩( 'ω' )و ////

ちょっとした雑談

前回pythonの環境構築を行った時はOS Xのときだったので、OSをアップデートしたことによるエラーが多発して、正直焦りました(^_^;)
ほんとはもっとスムーズに環境構築して、スマートな記事を投稿しようと思っていたのですが、世の中うまくいきませんね...
でもとりあえず環境構築はやりきることができたので、良いpython LIFEを過ごしたいものです!

参考にした記事

Pythonの仮想環境構築(2017年版) pyenvとpyenv-virtualenvとvirtualenvとvirtualenvwrapperとpyvenvとvenv
HomebrewのインストールからpyenvでPythonのAnaconda環境構築までメモ
MacのHomebrewでpyenv-virtualenv環境を作る
HighSierraにしてpyenvからpython入れようとしたら失敗した”The Python ssl extension was not compiled. Missing the OpenSSL lib?”
High Sierra(macOS 10.13)でpyenvがエラーになった時に対処した方法

29
35
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
29
35