Skip to content

Instantly share code, notes, and snippets.

@vhanla
Created December 27, 2024 03:13
Show Gist options
  • Save vhanla/774fcfb7577c29e19ccd552a223ca87a to your computer and use it in GitHub Desktop.
Save vhanla/774fcfb7577c29e19ccd552a223ca87a to your computer and use it in GitHub Desktop.
A .bat to uninstall all pip freeze packages showing a progress
@echo off
setlocal enabledelayedexpansion
:: Check Python and pip
echo Checking if Python and pip are installed...
python --version >nul 2>&1
IF %ERRORLEVEL% NEQ 0 (
echo ERROR: Python is not installed or not added to the PATH.
exit /b 1
)
pip --version >nul 2>&1
IF %ERRORLEVEL% NEQ 0 (
echo ERROR: pip is not installed or not added to the PATH.
exit /b 1
)
echo Python and pip are installed.
:: Confirm uninstallation
set /p confirm="Are you sure you want to uninstall all installed Python packages? This action is irreversible. (Y/N): "
IF /I NOT "%confirm%"=="Y" (
echo Operation canceled. No packages were uninstalled.
exit /b 0
)
:: First attempt with pip list
echo.
:: Count total packages first
echo.
echo Counting packages...
set /a total=0
for /f "skip=2 tokens=1" %%a in ('pip list') do set /a total+=1
if %total% EQU 0 (
echo No packages found to uninstall.
exit /b 0
)
echo Found %total% packages to uninstall.
echo.
:: Get start time in seconds since midnight
for /f "tokens=1-3 delims=:." %%a in ("%time%") do (
set /a start_seconds=%%a*3600 + %%b*60 + %%c
)
:: Initialize counters
set /a count=0
set /a last_seconds=start_seconds
set /a total_elapsed=0
set /a stop=0
echo Phase 1: Uninstalling standard packages...
for /f "skip=2 tokens=1" %%a in ('pip list') do (
:: Ctrl-C ignore if stop is 1
if "!stop!"=="1" (
goto endLoop
)
set /a count+=1
:: Calculate current time
for /f "tokens=1-3 delims=:." %%a in ("%time%") do (
set /a current_seconds=%%a*3600 + %%b*60 + %%c
)
:: Calculate elapsed time
set /a elapsed_seconds=current_seconds-start_seconds
if !elapsed_seconds! lss 0 set /a elapsed_seconds+=86400
:: Format elapsed time
set /a elapsed_min=elapsed_seconds/60
set /a elapsed_sec=elapsed_seconds%%60
:: Display progress
echo [%elapsed_min%m%elapsed_sec%s] Uninstalling %%a... !count!/%total%
:: Uninstall package
pip uninstall -y %%a
:: Detect Ctrl-C
if errorlevel 2 set "stop=1"
)
:endLoop
endlocal
echo.
echo All packages have been processed.
echo If you want to uninstall Python itself, please proceed with uninstalling Python via "Apps and Features" or using the Python uninstaller.
pause
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment