mac上Python多版本共存(python2.7.10和python3.5.0)

mingaixin發表於2017-01-18

本文的實現目標是在mac上安裝一個python3.5.0的版本,跟當前系統自帶的python2.7.10共存.
檢視當前版本號

python -V
2.7.10

安裝配置Python版本管理器pyenv

1. 安裝pyenv

brew install pyenv
安裝過程中,遇到一個一個問題Error: parent directory is world writable but not sticky

2. 根據提示需要新增變數

if which pyenv > /dev/null; then eval "$(pyenv init -)"; fi
export PYENV_ROOT=/usr/local/var/pyenv

因為我已經安裝了zsh,所以需要在~/.zshrc中將上面的兩句加入到檔案的末尾,最後執行
source ~/.zshrc

3. 檢視已經安裝了哪些版本的Python

pyenv versions
其中版本號前面有*號的就是當前生效的版本,檢視當前生效的版本也可以用
pyenv version

4. 安裝指定版本的Python

pyenv install 3.5.0
#安裝完成後必須rehash
pyenv rehash

安裝過程中,也是出現報錯BUILD FAILED (OS X 10.10.5 using python-build 20160130),解決辦法見pyenv BUILD FAILED解決方法

5. 切換和使用指定的版本Python版本有3種方法

➜  ~ pyenv
pyenv 20150310
Usage: pyenv <command> [<args>]

Some useful pyenv commands are:
   commands    List all available pyenv commands
   local       Set or show the local application-specific Python version
   global      Set or show the global Python version
   shell       Set or show the shell-specific Python version
   install     Install a Python version using python-build
   uninstall   Uninstall a specific Python version
   rehash      Rehash pyenv shims (run this after installing executables)
   version     Show the current Python version and its origin
   versions    List all Python versions available to pyenv
   which       Display the full path to an executable
   whence      List all Python versions that contain the given executable

See `pyenv help <command>' for information on a specific command.
For full documentation, see: https://github.com/yyuu/pyenv#readme

特別建議:

系統全域性用系統預設的Python比較好,不建議直接對其操作
pyenv global system
用local進行指定版本切換,一般開發環境使用。
pyenv local 2.7.10
對當前使用者的臨時設定Python版本,退出後失效
pyenv shell 3.5.0
取消某版本切換
pyenv local 3.5.0 --unset

優先順序關係:shell——local——global

#####另外最重要的一點,當執行了pyenv shell/local/global 命令後,一定要執行 source ~/.zshrc ,不然切換版本就不會生效。

最後執行

➜  ~ pyenv versions
  system
* 3.5.0 (set by PYENV_VERSION environment variable)
➜  ~
➜  ~ python -V
Python 3.5.0

參考資料:

Mac多Python版本共存,多個獨立Python開發環境切換

相關文章