Quick script to (re)create my python virtualenv

When working on rst2pdf, I use pyenv as I’ve written about before. Recently, I’ve found myself needing to recreate virtualenvs for various Python versions and then recreate them to easily reset the list of packages installed into them via pip.

To my my life easier, I created a script that I can run from the command line:

$ newenv rst2pdf-dev-py3.9 3.9.5

This creates a new virtualenv called rst2pdf-dev-py3.9 from Python version 3.9.5, upgrade pip and install pytest, pytest-xdist & pre-commit for me. It will then switch this directory to use the new virtualenv using pyenv local. If the virtualenv already exists, it deletes it.

This is the script if anyone else finds it useful (or I lose it!):

~/bin/newenv:

#!/usr/bin/env bash

# Exit if any command fails
set -e

venv=”$1″
version=”$2″

if [ -z “$venv” ]; then
echo “USAGE: newenv []”
echo “e.g.: newenv rst2pdf-395-deps”
exit 1
fi

if [ -z “$version” ]; then
# Use latest installed python version if not specified
version=$(pyenv versions –bare | grep -E ‘^3.[0-9]+.[0-9]+$’ | sort -rn | head -n 1)
fi

venv=”$1″
version=${2:-“$latest_py_version”}

echo “Creating $venv (v$version)…”

pyenv uninstall -f “$venv”
pyenv virtualenv “$version” “$venv” > /dev/null
pyenv local “$venv”
pip -q install –upgrade pip
pip -q install pytest pytest-xdist pre-commit
#pip -q install pip-tools pip-review setuptools wheel twine

echo “Done”

Maybe it’ll be helpful to you, especially if you adapt it, as making our lives easier via simple scripts is worth it!

Leave a Reply

Your email address will not be published. Required fields are marked *