Skip to content

Instantly share code, notes, and snippets.

@todgru
Last active February 17, 2025 22:20
Show Gist options
  • Save todgru/4d390d80154f90bf692ce9cfb1ca10a9 to your computer and use it in GitHub Desktop.
Save todgru/4d390d80154f90bf692ce9cfb1ca10a9 to your computer and use it in GitHub Desktop.
python virtual environments with autoload version

Mac OS X python virtual environments setup for new or existing projects

install pyenv

# install pyenv
curl https://pyenv.run | bash

# set env vars to support pyenv
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(pyenv init -)"' >> ~/.zshrc

# restart shell
exec "$SHELL"
# install pyenv-virtualenv plugin
git clone https://github.com/pyenv/pyenv-virtualenv.git $(pyenv root)/plugins/pyenv-virtualenv

# autoload python version for your project
echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.zshrc

# reload she
exec "$SHELL"

setup existing projects

If your project already has a .python-version file, use the name in the file as your name for your local python virtual environment:

# use pyenv to install a version of python
pyenv install my-projects-python-3.x.y

# in your project directory
pyenv virtualenv <my-projects-python-3.x.y> <name-in-.python-version>
pyenv activate <name-in-.python-version>
pyenv local <name-in-.python-version>

Example

my project has a .python-version file with the folowing contents:

My-Cool-Project-3.12.0

I cd into my project, install python, create virtual environment, activate, and run local:

$ cd ~/todgru/my-cool-project
$ pyenv install 3.12.0
$ pyenv virtualenv 3.12.0 My-Cool-Project-3.12.0
$ pyenv activate My-Cool-Project-3.12.0
$ pyenv local My-Cool-Project-3.12.0 # creates .python-version if doesn't exist

the comand line prompt will now show the python virtual environment name, like:

$ cd ~/todgru/my-cool-project
(My-Cool-Project-3.12.0)
$

verify

$ python --version
Python 3.12.0
(My-Cool-Project-3.12.0)
$

setup new projects

Setup for a new project is the same steps as above. Running pyenv local <project-name> creates the .project-version file. Commit this file to your project repo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment