Skip to content

Instantly share code, notes, and snippets.

@clyang
Forked from ashwinvis/backup_venv.sh
Created May 15, 2023 16:02
Show Gist options
  • Save clyang/a9bf57ab57a6b92c80b75277aaf953a2 to your computer and use it in GitHub Desktop.
Save clyang/a9bf57ab57a6b92c80b75277aaf953a2 to your computer and use it in GitHub Desktop.
Backup virtualenv before a Python 3.x upgrade and restore / recreate after the upgrade
#!/bin/bash
cd ~
pip freeze --user --exclude-editable > REQUIREMENTS.txt
cd $WORKON_HOME # or wherever you store your virtualenvs
for activate in ./*/bin/activate
do
source $activate
echo $VIRTUAL_ENV
pip freeze --local --exclude-editable > $VIRTUAL_ENV/REQUIREMENTS.txt
deactivate
done
#!/bin/bash
OLD_PYTHON=python3.6
cd ~
rm -r .local/lib/$OLD_PYTHON
cd $WORKON_HOME
rm -r $(find -name $OLD_PYTHON -type d)
#!/bin/bash
cd ~
# rm .local/lib/python3.6
pip install --user -r REQUIREMENTS.txt
cd $WORKON_HOME
PYTHON_VERSION=$(python -c 'import sysconfig; print("python" + sysconfig.get_python_version())')
# New directory
export WORKON_HOME="./../$PYTHON_VERSION"
mkdir -p $WORKON_HOME
for VIRTUAL_ENV in ./*
do
# Detect which python was used
if [[ -d $VIRTUAL_ENV/lib_pypy ]]; then
PY="pypy3"
else
PY=$(basename `ls $VIRTUAL_ENV/lib` | awk -F. '{print $1}')
fi
echo "Recreate $VIRTUAL_ENV using $PY in $WORKON_HOME"
if [[ -f $VIRTUAL_ENV/.project ]]; then
PROJECT=$(cat $VIRTUAL_ENV/.project)
pew new -p $PY -r $VIRTUAL_ENV/REQUIREMENTS.txt -a $PROJECT $VIRTUAL_ENV
else
pew new -p $PY -r $VIRTUAL_ENV/REQUIREMENTS.txt $VIRTUAL_ENV
fi
done
cd $WORKON_HOME
for venv in *
do
pew restore $venv
done
pip-restore-any(){
# Installs any version
# Run `pew toggleglobalsitepackages` if wheels are not available
pip install $(cat $VIRTUAL_ENV/REQUIREMENTS.txt | awk -F"==" '{printf $1" " }')
}
pip-restore-exact(){
# Installs exact version
pip install -r $VIRTUAL_ENV/REQUIREMENTS.txt
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment