Skip to content

Instantly share code, notes, and snippets.

@numpde
Created May 21, 2023 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save numpde/a25b68577e05bd347ebd8855e097a149 to your computer and use it in GitHub Desktop.
Save numpde/a25b68577e05bd347ebd8855e097a149 to your computer and use it in GitHub Desktop.
Find python venv folders, perform pip freeze and uninstall all packages.
#!/bin/bash
IFS=$'\n'
# Find all unique directories containing 'venv*' subdirectories
for dir in $(find . -type d -name "venv*" -printf '%h\n' | sort -u)
do
echo "Found directory: $dir"
# Find all requirement files in the directory
for req_file in $(ls "$dir"/requirements*.txt 2>/dev/null)
do
echo "First 5 lines of $req_file:"
head -n 5 "$req_file"
done
# Loop over all venv* subdirectories in the current directory
for venv in $(find "$dir" -maxdepth 1 -type d -name "venv*")
do
if [ -f "$venv/pyvenv.cfg" ]; then
echo "Found virtual environment in $venv"
base_name=$(basename "$venv")
suffix="${base_name#venv}"
requirement_file="$dir/requirements$suffix.txt"
read -p "Clean up $venv? (y/n) - " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
echo "Activating $venv"
source "$venv"/bin/activate
echo "Generating requirements file"
touch "$requirement_file"
pip freeze | cat - "$requirement_file" | sort | uniq > temp.txt && mv temp.txt "$requirement_file"
echo "Uninstalling all packages"
pip uninstall -y -r "$requirement_file"
echo "Deactivating $venv"
deactivate
fi
fi
done
done
# Reset the IFS to its original value
unset IFS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment