A Better Virtual Environment Helper

Jan 9, 2025

Back in 2020, I put together a very simple virtual environment helper script for Python virtual environments in Windows. One issue this previous incarnation had was the inability to walk up the tree structure, looking for virtual environment folders above the current level. As a result, you always had to be in the root of the project to activate or deactivate the virtual environment.

I've finally spent a little time fixing this, and the improved script is below. The script will now walk up the tree structure, allowing you to activate or deactivate the environment, regardless of your depth in the tree. Just save the contents as a batch file named work.bat, put it in your PATH, and use either work or work off to activate or deactivate the environment, respectively.

@echo off

set "startDir=%cd%"

:: Get the drive letter from the start directory
for %%D in (%startDir%) do set "drive=%%~dD"

:: Traverse upwards from here
set "currentDir=%startDir%"
:loop

:: Stop if we reach the root of the drive
if "%cd%"=="%drive%\" (
    echo Unable to locate venv folder in this tree
    exit /b
)

if exist "%cd%\venv" (
    if "%1" == "off" (
        echo Deactivating virtual environment
        call "%cd%\venv\Scripts\deactivate.bat"
        echo.
    ) else (
        echo Activating virtual environment
        call "%cd%\venv\Scripts\activate.bat"
    )
    cd %startDir%
    exit /b
)

:: Move up one level
cd ..
goto loop

No comments (yet!)

Leave a Comment

Ignore this field:
Never displayed
Leave this blank:
Optional; will not be indexed
Ignore this field:
Both Markdown and a limited set of HTML tags are supported
Leave this empty: