Pedram's Web Blog

Things I Learned

The shortest guide to working with Python virtual environments

|

No boilerplate, no fluff, just the essentials. Here’s the correct way to use Python virtual environments. My way. No other way is good. Don’t think about doing it any other way.

  1. Install pyenv and pyenv-virtualenv
  curl https://pyenv.run | bash
git clone https://github.com/pyenv/pyenv-virtualenv.git $(pyenv root)/plugins/pyenv-virtualenv 
  1. Add environment variables to your startup files. This is for zsh.
  echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(pyenv init -)"' >> ~/.zshrc 
  1. Install a Python version you care about
  pyenv 3.11 
  1. Create a virtual environment
  pyenv virtualenv 3.11 myenv 
  1. Activate the virtual environment and set it to always run from this folder
  mkdir my-python-project
pyenv local myenv 

That’s it. Never think about Python environments again.