Skip to content

Instantly share code, notes, and snippets.

@fkztw
Last active November 12, 2020 07:09
Show Gist options
  • Save fkztw/e1bf93a4a8170fabac24db9aee686caf to your computer and use it in GitHub Desktop.
Save fkztw/e1bf93a4a8170fabac24db9aee686caf to your computer and use it in GitHub Desktop.
A simple script to fix and reinstall all modules for each virtualenv of a user after upgrading whole system Python. https://blog.m157q.tw/posts/2015/10/07/fix-virtualenv-after-an-upgrade-of-python/
#!/usr/bin/env bash
VIRTUALENVS_ROOT_DIR="${HOME}/.virtualenvs"
ACTIVE_SH_PATH="/bin/activate"
for dir in `find ${VIRTUALENVS_ROOT_DIR} -type d -maxdepth 1`
do
if [[ ${dir} == ${VIRTUALENVS_ROOT_DIR} ]]; then
continue
fi
source ${dir}${ACTIVE_SH_PATH}
ENV_PATH="$(dirname "$(dirname "$(which pip)")")"
SYSTEM_VIRTUALENV="$(which -a virtualenv|tail -1)"
echo
echo "Ensure the root of current virtualenv:"
echo " $ENV_PATH"
read -p "Say no if you are not sure (y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
read -p "Reinstall all packages of this virtualenv after upgraded? (y/N) " -n 1 -r
if [[ $REPLY =~ "^[Yy]$" ]]; then
echo "Dump pip freeze for current virtualenv into requirements.temp"
pip freeze > requirements.temp
fi
VIRTUALENV_PYTHON_VERSION=`python --version`
echo "Removing old symbolic links......"
find "$ENV_PATH" -type l -delete -print
echo "Creating new symbolic links......"
echo ${VIRTUALENV_PYTHON_VERSION}
if [[ $VIRTUALENV_PYTHON_VERSION =~ "Python 2" ]]; then
echo "Use Python 2 environment for this virtualenv"
$SYSTEM_VIRTUALENV "$ENV_PATH" --python=python2
elif [[ $VIRTUALENV_PYTHON_VERSION =~ "Python 3" ]]; then
echo "Use Python 3 environment for this virtualenv"
$SYSTEM_VIRTUALENV "$ENV_PATH" --python=python3
else
echo "Unknown Python version of this virtualenv"
fi
if [[ $REPLY =~ "^[Yy]$" ]]; then
echo "Reinstall modules from previous dumped pip freeze result."
pip install -r requirements.temp
echo "Remove requirements.temp"
rm requirements.temp
fi
fi
deactivate
done
echo "Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment