Pyenv on Mac
Posted on Fri, 19 May 2017 in Python
It can be painful to manage several Python versions on one laptop. However, it is a very common situation. Usually, developers have many projects that require different Python versions. There are a couple of variants to deal with it. My favourite is pyenv with virtualenv plugin. I used to use Homebrew itself to do that, but it wasn't so flexible.
Installation
$ brew update
$ brew install pyenv
$ brew install pyenv-virtualenv
$ echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
$ echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bash_profile
Basic usage
I strongly recommend making a separate virtual environment for each project. Sometimes it is necessary to make several environments for one project. For example, if you want to use mypy for a Python 2 project.
First of all get the list with available versions.
$ pyenv install --list
There are a lot of variants including PyPy and Stackless Python. If the latest version is not in the list, update Homebrew formula:
$ brew upgrade pyenv
Usually, new Python versions appear in the list in a day or two.
There are 3 steps to prepare virtualenv for your project:
- Install new Python version if needed
- Make new virtualenv
- Activate environment
$ pyenv install 3.6.0
$ pyenv virtualenv 3.6.0 my-project-venv
$ cd /to/my/project/folder
$ pyenv local my-project-venv
That's it.
In case of using PyCharm, you should create a new Python SDK with home path equal to ~/.pyenv/versions/my-project-venv
Got a question? Hit me on Twitter: avkorablev