Automating Python Virtual Environment Creation with Git Worktree on Windows
Because AI can run in multiple instances, I often need to create Git worktrees and Python virtual environments on Windows to support parallel project development. To improve efficiency, I asked AI for a solution that automates these tasks whenever a new worktree is created.
Environment:
- Windows 11
- PowerShell 7.5
Put the function below into your $PROFILE, so each time you open PowerShell you can use the gwa command to create a new worktree and virtual environment.
$PROFILE is the path to your PowerShell profile script, usually located at C:\Users\<YourUsername>\Documents\PowerShell\Microsoft.PowerShell_profile.ps1.
# Check the actual profile path
$PROFILE
# Create it if it does not exist
if (!(Test-Path $PROFILE)) { New-Item -ItemType File -Path $PROFILE -Force }
# Open it in an editor
notepad $PROFILE
# Put this in $PROFILE
function gwtadd {
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Path,
[Parameter(ValueFromRemainingArguments = $true)]
[string[]]$Rest
)
# 1) Create worktree
git worktree add $Path @Rest
if ($LASTEXITCODE -ne 0) {
Write-Error "git worktree add failed."
return
}
# 2) Enter the new directory
$fullPath = Resolve-Path $Path
Push-Location $fullPath
try {
# 3) Create venv
& "C:\Users\User\AppData\Local\Programs\Python\Python312\python.exe" -m venv .venv
if ($LASTEXITCODE -ne 0) {
Write-Error "venv creation failed."
return
}
# 4) Activate venv (dot-source so it applies to the current shell)
. .\.venv\Scripts\Activate.ps1
# 5) Install dependencies (if requirements.txt exists)
if (Test-Path .\requirements.txt) {
python -m pip install --upgrade pip
pip install -r requirements.txt
} else {
Write-Host "requirements.txt not found, skip pip install."
}
Write-Host "Worktree ready: $fullPath"
}
finally {
Pop-Location
}
}
Set-Alias gwa gwtadd
Usage:
# For example, create and switch to a new branch
gwa ..\gl-auto-test-core-feat -b feat/my-branch