Install multiple versions of python i OS X

If you need install multi python versions in the host, and use different version of python for different application, it is very useful to use pyenv to manage different version installed in the host. For example, I have python 3.6 and 2.7 installed in my Mac, where python –version shows default version is 3.6

mac-c02t6npagtfj:ansible_test grayin$ python –version

Python 3.6.4

But I want to change my default python to version 2.7 in my Mac, and use pip in package 2,7 to install new packages in python2.7.

What I have done is to install pyenv first, then use pyenv to reinstall version 2,7 and 3.6, after that, change version of python used in the host:

$ brew update
$ brew install pyenv

To enable pyenv in your Bash shell, you need to run:

$ eval "$(pyenv init -)"
After this, we can use pyenv to reinstall python
$ pyenv install 2.7.14
$ pyenv install 3.6.4

 

And you can switch between python versions with the command:

$ pyenv global 2.7.14

Also you can set a python version for the current directory with:

$ pyenv local 3.6.4
mac-c02t6npagtfj:ansible_test grayin$ pyenv versions
  system
  2.7
* 2.7.14 (set by /Users/grayin/.pyenv/version)
  3.6.4
After this:
mac-c02t6npagtfj:ansible_test grayin$ python --version
Python 2.7.14
mac-c02t6npagtfj:ansible_test grayin$ pip --version
pip 9.0.1 from /Users/grayin/.pyenv/versions/2.7.14/lib/python2.7/site-packages (python 2.7)

Even pip as default is attached to python2.7 now.

Pyenv can be helpful to avoid home-brew lost track of python

Sometime people may feel very confused that he/she has installed a package already but when importing it in the script, it would show that package is not installed or can not find the module.  This is because that when pip is attached to version 2.7, all package installed using pip will be installed for version 2.7, when pip is attached to version 3.6, all package installed using pip will be for version 3.6.  If version 2.7 is used but actually pip is attached to version 3.6, package will be installed in version 3.6.

Another alternative to address this issue is to use different /path/pip to install the package for the different version of python. Anyhow I have not tested this option.

Some also recommend the easier way for using pip in different version installation:

$ pip2.6 install otherpackage
$ pip2.7 install mybarpackage

However, this does not work for me:

mac-c02t6npagtfj:ansible_test grayin$ pip2.7 --version
pip 9.0.1 from /Users/grayin/.pyenv/versions/2.7.14/lib/python2.7/site-packages (python 2.7)
mac-c02t6npagtfj:ansible_test grayin$ pip3.6 --version
pyenv: pip3.6: command not found
The `pip3.6' command exists in these Python versions:
  3.6.4
mac-c02t6npagtfj:ansible_test grayin$ pip3.6.4 --version
-bash: pip3.6.4: command not found

 

Advertisements