You are working on different projects that require different versions of Python? You’re tired of switching between them?
Luckily, Pyenv is here to help you out.
pyenv lets you easily switch between multiple versions of Python. It’s simple, unobtrusive, and follows the UNIX tradition of single-purpose tools that do one thing well.
Today, I will guide you through the steps of making it work with default terminal or with zsh.
Before we start, brew is used to install pyenv. If you’re already installed brew, skip this step. Otherwise, install brew through this link: https://brew.sh
Homebrew installs packages to their own directory and then symlinks their files into
Step 1: Install pyenv
$ brew install pyenv
Step 2: Add config to load pyenv every time we open a new shell
If you’re using default mac Terminal:
$ echo 'if which pyenv > /dev/null; then eval "$(pyenv init -)"; fi' >> ~/.bash_profile
Else if you are using zsh instead:
$ echo 'if which pyenv > /dev/null; then eval "$(pyenv init -)"; fi' >> ~/.zprofile
Now restart your terminal.
Step 3: Confirm if it is properly set up
$ which python
It will output something like this:
$ which python /Users/duchoang/.pyenv/shims/python
Step 4: Install python versions
To list all python versions that can be installed using pyenv:
$ pyenv install -l
This will output a really long list like:
Available versions: 2.1.3 2.2.3 . . . stackless-3.3-dev stackless-3.3.5 stackless-3.4.1 stackless-3.4.2
Choose the version you want, example 3.6.2. To install:
$ pyenv install 3.6.2
Wait for downloading and installing to complete.
If an error occurs, with the message like:
zipimport.ZipImportError: can't decompress data; zlib not available
Try this in your terminal:
$ CFLAGS="-I$(brew --prefix openssl)/include -I$(xcrun --show-sdk-path)/usr/include" \ LDFLAGS="-L$(brew --prefix openssl)/lib" \
> pyenv install 3.6.2
Step 5: Switch between different python versions
To list all installed versions:
$ pyenv versions
This will output:
* system (set by /Users/duchoang/.pyenv/version) 3.6.2
To switch to 3.6.2 as global python version:
$ pyenv global 3.6.2
You can also change the version of python to a local folder:
$ cd ~/your/local-project/
$ pyenv local 3.2.6
This will create a `.python-version` file and the version of python inside the project will be set despite the global version.