Published on

Managing python venvs with pyenv on macOS

Authors

Why use virtual environments?

Whenever you do any kind of python development, you should always use a virtual environment. There are several reasons for this:

  • The main reason being that you don't want to mess up your system python installation
  • Every project requires different dependencies
  • You might need different python versions for different projects

Setting up pyenv and pyenv-virtualenv

By far my favourite way to manage python environments is with pyenv. Pyenv is a simple python version manager that allows you to install different python versions on your computer and easily switch between them.

Since we're using macOS we can install pyenv with homebrew.

brew update
brew install pyenv

After installing pyenv, run the following to add some useful commands to your shell configuration file and restart your shell.

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
exec "$SHELL"

Next we're gonna install pyenv-virtualenv for managing virtual environments.

brew install pyenv-virtualenv

Lastly, run this command to add another useful line to your shell configuration file (so we can use pyenv virtualenv in the terminal) and restart your shell again.

echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bashrc
exec "$SHELL"

Using pyenv

Run the following command to list all python versions and virtual environments that you currently have installed (should be fairly empty at this point).

pyenv versions

There is an asteriks next to the python version that is currently active.

To install a specific python version, for example 3.10.12, run the following command.

pyenv install 3.10.12

And then switch to it using

pyenv global 3.10.12

Using pyenv-virtualenv

Now we can create virtual environments for a python version we have installed.

First we can list all virtual environments that we have (should be empty).

pyenv virtualenvs

To create a new virtual environment, run the following command. This will create a virtual environment called myenv using python version 3.10.12 in the default location ~/.pyenv/versions.

pyenv virtualenv 3.10.12 myenv

Lastly, to activate the virtual environment, run the following command.

pyenv activate myenv

Optional: jupyter notebooks

If you want to use jupyter notebooks with your virtual environment, you can install the ipykernel package.

pip install ipykernel

Then run the following command to be able to select your virtual environment in jupyter notebooks (you can give it any name, I'm using myenv here as an example)

ipython kernel install --user --name=myenv