Installing Python and managing Python versions with pyenv (bonus venv)

Step 1: Meet your default python

You are on Mac OS. When you run python in your terminal you see this. You have Python 2.7.10.

This is your default python. You can do things like add > 8+8

Step 2: Meet your modules

From your interpreter you can see your available modules by asking for “help”

> help("modules)"

Note that you have a bunch of modules – including “antigravity” 🛸 Try it!

> import antigravity

But where are these modules?

For this investigation you need to import the “sys” module – which gives you access to the “system” – and print your “path” – which will print *most* of the folders that python will search for your modules.

> import sys

> print(sys.path)

* Note: if you ls into any of these folders, you will find a bunch of modules

NOTE: Python 2 was sunset on January 2020 so use Python version 3.x

Step 3: installing python with “pyenv”

The main job of pyenv is to manage which version of python you prefer to run.

How?

pyenv prepends a directory to your $PATH variable and hijacks every python or pip command you run. Then it tries to find your “preferred” python version to run.

How does it know my preferred version?

pyenv will first check the PYENV_VERSION environment variable (if set), then will move onto finding a .python-version file in the current directory, then look in the parent directory, then that parents directory, all the way up to the root. If it doesn’t find that file, it will search for a $(pyenv root)/version file and if it doesn’t find that, it will simply use your “system” python.

Step 1: brew install pyenv

Step 2: add the pyenv init command to your .bash_profile with this command

$ echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bash_profile

Step 3: run your bash profile to make sure the changes propagate

source ~/.bash_profile

Now, if you run python you will see that you are still on version 2.7.10 (or whatever your system python was from the start). This is because you have not yet set your preferred python anywhere else, and the search landed on your system python.

Use pyenv install --list to list all available python versions.

Use pyenv install --list|awk '$1 ~ /^3/'|tail -n 10 to list the last 10 releases

Step 4: install a version of python that works with your favorite library

$ pyenv install 3.5.5

Step 5: create a .python-version file in your project

$ echo 3.5.5 > .python-version

Step 6: run python

$ python

Bonus: create virtual environments with venv

As of 3.5 venv is the recommended way to create virtual environments.

Step 1: Create a new virtual environment. Here we call it “myenv”.

python -m venv myenv

source myenv/bin/activate

Later we deactivate the environment with…

$ deactivate