pythonwindowspowershellvirtualenv

Is there a way to automate activating the virtualenv in Powershell (in Windows)?


I know that to activate virtualenv it's just .venv/Scripts/activate.ps1 but I was wondering if there's a way of having powershell do it automatically?

Existing ones just talk about activating it, but not how to have Powershell do it automatically

I am looking for something like this but in Powershell

Automating virtualenv activation/deactivation in zsh


Solution

  • Add something like the following to your PowerShell $PROFILE file:

    $ExecutionContext.SessionState.InvokeCommand.LocationChangedAction =
      [Delegate]::Combine(
        $ExecutionContext.SessionState.InvokeCommand.LocationChangedAction,
        [EventHandler[System.Management.Automation.LocationChangedEventArgs]] { 
    
          # Look for a virtual-environment activation script relative to the
          # new working directory and, if found, execute it.
          if ($script = Get-Item -ErrorAction Ignore -LiteralPath ./.venv/Script/activate.ps1) {
            Write-Verbose -Verbose "Activating virtual environment in $PWD..."
            & $script
          }
    
        }
      )
    

    Note: