Skip to content

Instantly share code, notes, and snippets.

@jaysin586
Last active November 18, 2024 21:21
Show Gist options
  • Save jaysin586/ba1d1bc1547c0bc0fac6bcab4e849a8d to your computer and use it in GitHub Desktop.
Save jaysin586/ba1d1bc1547c0bc0fac6bcab4e849a8d to your computer and use it in GitHub Desktop.
PyENV Update Script
# A function to update the python version in a pyenv virtualenv
# Usage: pyenv_update <version>
# Example: pyenv_update 3.9.7
# Note: This will remove the virtualenv and recreate it.
pyenv_update() {
PYENV_FILE=.python-version
PYENV_FREEZE_FILE=.requirements-lock.txt
# Check if version argument is provided
if [ -z "$1" ]; then
echo "❌ Error: Please specify the version of python to update to."
echo "Usage: pyenv_update <version>"
echo "Example: pyenv_update 3.9.7"
return 1
fi
# Check if .python-version exists
if [ ! -f "$PYENV_FILE" ]; then
echo "❌ Error: $PYENV_FILE does not exist in current directory."
return 1
fi
echo "πŸ” Current directory: $(pwd)"
pyenv_version=$(head -n 1 $PYENV_FILE)
echo "πŸ“¦ Updating from Python $pyenv_version to $1"
# Install new Python version if needed
echo "πŸ”§ Installing Python $1 if not already installed..."
pyenv install -s "$1"
# Save current dependencies
echo "πŸ“ Saving current dependencies..."
pip freeze > $PYENV_FREEZE_FILE
# Remove old virtualenv
echo "πŸ—‘οΈ Removing old virtualenv..."
pyenv uninstall -f $pyenv_version
# Create new virtualenv
echo "πŸ—οΈ Creating new virtualenv..."
pyenv virtualenv $1 $pyenv_version
# Upgrade pip and reinstall dependencies
echo "πŸ”Ό Upgrading pip..."
pip install --upgrade pip >/dev/null 2>&1
echo "πŸ“₯ Reinstalling dependencies..."
pip install -r $PYENV_FREEZE_FILE >/dev/null 2>&1
# Cleanup
rm $PYENV_FREEZE_FILE
echo "βœ… Successfully updated to Python $1"
echo "🐍 Current Python version: $(python --version)"
}
@farhadhu
Copy link

Ur the best <3

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