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
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:
This installs an event handler that executes whenever the current location (directory) is changed in the current session and executes a script located in ./.venv/Script/activate.ps1
relative to the new current directory, if present.
& $script | Out-Host
No attempt is made to deactivate a previously active virtual environment or to detect if a subdirectory of a directory containing a virtual environment is changed to, though doing these things would be possible with additional effort.
Through use of [Delegate]::Combine()
, the code preserves any preexisting event handler.
{ ... }
) directly to $ExecutionContext.SessionState.InvokeCommand.LocationChangedAction