LoginSignup
0
1

More than 1 year has passed since last update.

pyenv globalでversionを切り替えたのに切り替わらない

Posted at

環境

  • macOS Big Sur 11.3.1
  • pyenv 1.2.27

事象

pyenvでPython3.8.9をインストールしました。
pyenv global 3.8.9 でpythonのversionをスイッチしても、
もともとMacにインストールされている古いPythonを見に行ってしまうという事象です。

% pyenv versions
  system
* 3.8.9 (set by /Users/〇〇/.pyenv/version)

% python --version
Python 2.7.16

% which python
/usr/bin/python

結論

pythonの実行Pathが差し替えられていない。
ゆえに、Pathを差し替えてあげるために以下をprofileに追加する。
私はzshを使用しているため、 ~/.zshrc に書き込んだ。

eval "$(pyenv init -)"

ターミナルを再起動するか、source ~/.zshrc コマンドで設定を反映する。
pythonのバージョンとPathを確認する。

% which python          
/Users/〇〇/.pyenv/shims/python

% pyenv versions
  system
* 3.8.9 (set by /Users/suto/.pyenv/version)

% python -V      
Python 3.8.9

原因と補足

原因はPythonの環境変数Pathが書き変わってなかったことでした。
Pathを正しく書き換えてあげると、 pyenv でインストールしたversionを見に行くようです。

githubにあるpyenvのREADMEを確認してみると、Pythonの環境変数Pathに :shims というが入ることによって複数のversionを使い分けられるというようなことが書いてありました。
(恥ずかしながら英語はあまりできないので理解が違っているかもしれません。。。)

pyenv works by inserting a directory of shims at the front of your PATH:
$(pyenv root)/shims:/usr/local/bin:/usr/bin:/bin
Through a process called rehashing, pyenv maintains shims in that directory to match every Python command across every installed version of Python—python, pip, and so on.

※ 以下から抜粋しました。
https://github.com/pyenv/pyenv

また、今回実行するようにしたinitコマンドですが中身は以下のようになってました。
pyenvの初期化を毎度行うようにしないと、次にターミナルを開いた時にpythonのPathが元に戻ります。
ですので ~/.zshrc に初期化コマンドを書くことで、ターミナルを起動した時に初期化コマンドが実行され、pythonのPathを差し替えてくれるみたいです。
※ 余談ですが、 .xxxrc のrcは run command の意です。

% echo "$(pyenv init -)"
export PATH="/Users/〇〇/.pyenv/shims:${PATH}"
export PYENV_SHELL=zsh
source '/usr/local/Cellar/pyenv/1.2.27/libexec/../completions/pyenv.zsh'
command pyenv rehash 2>/dev/null
pyenv() {
  local command
  command="${1:-}"
  if [ "$#" -gt 0 ]; then
    shift
  fi

  case "$command" in
  rehash|shell)
    eval "$(pyenv "sh-$command" "$@")";;
  *)
    command pyenv "$command" "$@";;
  esac
}
0
1
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
1