2022/06/28

pyenvの導入

macのpythonのバージョンは3.9.13で、raspberry piでsphinx文書の作成をしていたのが3.7.3であったので、その環境をmac上で構築するためにmacにpyenvを導入してみた

本当の導入理由

pip install -r requirements.txtをしたときに、pkg-resources==0.0.0はversionがおかしいというエラーが出たので、pip freeze > requirementes.txtを実行したraspberry piと同じpythonのversionにしたら動くと思ったのがきっかけ。
実際pdg-resources==0.0.0は不要なので消すというのが正しい対処だった
pip freezeをすると暗黙的にインストールされてしまうものらしい

導入方法

% brew install pyenv

.zshrcに以下の記述をして環境変数とinitコマンドを追加する

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

パスが通り実行ができるか確認

% pyenv -v
pyenv 2.3.1

pyenvでpythonのインストール

% pyenv install --list
...
  3.7.5
  3.7.6
  3.7.7
  3.7.8
  3.7.9
  3.7.10
  3.7.11
  3.7.12
  3.7.13
  3.8.0
  3.8-dev
  3.8.1
  3.8.2
  3.8.3
  3.8.4
  3.8.5
  3.8.6
  3.8.7
  3.8.8
  3.8.9
  3.8.10
  3.8.11
  3.8.12
  3.8.13
  3.9.0
  3.9-dev
  3.9.1
  3.9.2
  3.9.4
  3.9.5
  3.9.6
...

% pyenv install [version_num]

3.7.3がうまくインストールできなかった。
macOSで3.8よりも古いバーションのpythonはインストールできない不具合があるようで…
なんで失敗するのかはよくわからなかった

% pyenv install 3.7.3
python-build: use openssl@1.1 from homebrew
python-build: use readline from homebrew
Downloading Python-3.7.3.tar.xz...
-> https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tar.xz
Installing Python-3.7.3...
python-build: use tcl-tk from homebrew
python-build: use readline from homebrew
python-build: use zlib from xcode sdk

BUILD FAILED (OS X 12.4 using python-build 20180424)

Inspect or clean up the working tree at /var/folders/z2/jrh7t6ld2d37y15p59f135z00000gn/T/python-build.20220629010641.33405
Results logged to /var/folders/z2/jrh7t6ld2d37y15p59f135z00000gn/T/python-build.20220629010641.33405.log

Last 10 log lines:
                   ^
./Modules/posixmodule.c:8351:12: note: forward declaration of 'struct sf_hdtr'
    struct sf_hdtr sf;
           ^
./Modules/posixmodule.c:8431:15: error: implicit declaration of function 'sendfile' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
        ret = sendfile(in, out, offset, &sbytes, &sf, flags);
              ^
2 errors generated.
make: *** [Modules/posixmodule.o] Error 1
make: *** Waiting for unfinished jobs....

python3.7.2のインストール

% pyenv install --patch 3.7.2 < <(curl -sSL https://github.com/python/cpython/commit/8ea6353.patch\?full_index\=1)

このコマンドで無事インストールすることができた

pyenvの簡単な使い方

pyenvでpythonのバージョンを切り替える

% pyenv versions
* system (set by /Users/USER_NAME/.python-version)
  3.7.2
  3.8.9
% python3 -V
Python 3.9.13

% pyenv local 3.7.2
% python -V 
Python 3.7.2
% python3 -V
Python 3.7.2
% pyenv versions
  system
* 3.7.2 (set by /Users/USER_NAME/.python-version)
  3.8.9

% pyenv local 3.8.9
% python -V
Python 3.8.9
% python3 -V
Python 3.8.9
% pyenv versions
  system
  3.7.2
* 3.8.9 (set by /Users/USER_NAME/.python-version)

これで自由にバージョンの切り替えができて、元々macにインストールされていたpythonに切り替えることもできる

まとめ

勘違いから始まったpyenvの導入だが、これでいろんなバージョンのpython環境を使えるようになった

検索用タグ

python, pyenv

参考