Aguchi/image_recognition
0
1<#2.Synopsis3Activate a Python virtual environment for the current PowerShell session.4 5.Description6Pushes the python executable for a virtual environment to the front of the7$Env:PATH environment variable and sets the prompt to signify that you are8in a Python virtual environment. Makes use of the command line switches as9well as the `pyvenv.cfg` file values present in the virtual environment.10 11.Parameter VenvDir12Path to the directory that contains the virtual environment to activate. The13default value for this is the parent of the directory that the Activate.ps114script is located within.15 16.Parameter Prompt17The prompt prefix to display when this virtual environment is activated. By18default, this prompt is the name of the virtual environment folder (VenvDir)19surrounded by parentheses and followed by a single space (ie. '(.venv) ').20 21.Example22Activate.ps123Activates the Python virtual environment that contains the Activate.ps1 script.24 25.Example26Activate.ps1 -Verbose27Activates the Python virtual environment that contains the Activate.ps1 script,28and shows extra information about the activation as it executes.29 30.Example31Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv32Activates the Python virtual environment located in the specified location.33 34.Example35Activate.ps1 -Prompt "MyPython"36Activates the Python virtual environment that contains the Activate.ps1 script,37and prefixes the current prompt with the specified string (surrounded in38parentheses) while the virtual environment is active.39 40.Notes41On Windows, it may be required to enable this Activate.ps1 script by setting the42execution policy for the user. You can do this by issuing the following PowerShell43command:44 45PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser46 47For more information on Execution Policies: 48https://go.microsoft.com/fwlink/?LinkID=13517049 50#>51Param(52 [Parameter(Mandatory = $false)]53 [String]54 $VenvDir,55 [Parameter(Mandatory = $false)]56 [String]57 $Prompt58)59 60<# Function declarations --------------------------------------------------- #>61 62<#63.Synopsis64Remove all shell session elements added by the Activate script, including the65addition of the virtual environment's Python executable from the beginning of66the PATH variable.67 68.Parameter NonDestructive69If present, do not remove this function from the global namespace for the70session.71 72#>73function global:deactivate ([switch]$NonDestructive) {74 # Revert to original values75 76 # The prior prompt:77 if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {78 Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt79 Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT80 }81 82 # The prior PYTHONHOME:83 if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {84 Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME85 Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME86 }87 88 # The prior PATH:89 if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {90 Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH91 Remove-Item -Path Env:_OLD_VIRTUAL_PATH92 }93 94 # Just remove the VIRTUAL_ENV altogether:95 if (Test-Path -Path Env:VIRTUAL_ENV) {96 Remove-Item -Path env:VIRTUAL_ENV97 }98 99 # Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:100 if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {101 Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force102 }103 104 # Leave deactivate function in the global namespace if requested:105 if (-not $NonDestructive) {106 Remove-Item -Path function:deactivate107 }108}109 110<#111.Description112Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the113given folder, and returns them in a map.114 115For each line in the pyvenv.cfg file, if that line can be parsed into exactly116two strings separated by `=` (with any amount of whitespace surrounding the =)117then it is considered a `key = value` line. The left hand string is the key,118the right hand is the value.119 120If the value starts with a `'` or a `"` then the first and last character is121stripped from the value before being captured.122 123.Parameter ConfigDir124Path to the directory that contains the `pyvenv.cfg` file.125#>126function Get-PyVenvConfig(127 [String]128 $ConfigDir129) {130 Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"131 132 # Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).133 $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue134 135 # An empty map will be returned if no config file is found.136 $pyvenvConfig = @{ }137 138 if ($pyvenvConfigPath) {139 140 Write-Verbose "File exists, parse `key = value` lines"141 $pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath142 143 $pyvenvConfigContent | ForEach-Object {144 $keyval = $PSItem -split "\s*=\s*", 2145 if ($keyval[0] -and $keyval[1]) {146 $val = $keyval[1]147 148 # Remove extraneous quotations around a string value.149 if ("'""".Contains($val.Substring(0, 1))) {150 $val = $val.Substring(1, $val.Length - 2)151 }152 153 $pyvenvConfig[$keyval[0]] = $val154 Write-Verbose "Adding Key: '$($keyval[0])'='$val'"155 }156 }157 }158 return $pyvenvConfig159}160 161 162<# Begin Activate script --------------------------------------------------- #>163 164# Determine the containing directory of this script165$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition166$VenvExecDir = Get-Item -Path $VenvExecPath167 168Write-Verbose "Activation script is located in path: '$VenvExecPath'"169Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"170Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"171 172# Set values required in priority: CmdLine, ConfigFile, Default173# First, get the location of the virtual environment, it might not be174# VenvExecDir if specified on the command line.175if ($VenvDir) {176 Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"177}178else {179 Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."180 $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")181 Write-Verbose "VenvDir=$VenvDir"182}183 184# Next, read the `pyvenv.cfg` file to determine any required value such185# as `prompt`.186$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir187 188# Next, set the prompt from the command line, or the config file, or189# just use the name of the virtual environment folder.190if ($Prompt) {191 Write-Verbose "Prompt specified as argument, using '$Prompt'"192}193else {194 Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"195 if ($pyvenvCfg -and $pyvenvCfg['prompt']) {196 Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"197 $Prompt = $pyvenvCfg['prompt'];198 }199 else {200 Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"201 Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"202 $Prompt = Split-Path -Path $venvDir -Leaf203 }204}205 206Write-Verbose "Prompt = '$Prompt'"207Write-Verbose "VenvDir='$VenvDir'"208 209# Deactivate any currently active virtual environment, but leave the210# deactivate function in place.211deactivate -nondestructive212 213# Now set the environment variable VIRTUAL_ENV, used by many tools to determine214# that there is an activated venv.215$env:VIRTUAL_ENV = $VenvDir216 217if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {218 219 Write-Verbose "Setting prompt to '$Prompt'"220 221 # Set the prompt to include the env name222 # Make sure _OLD_VIRTUAL_PROMPT is global223 function global:_OLD_VIRTUAL_PROMPT { "" }224 Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT225 New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt226 227 function global:prompt {228 Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "229 _OLD_VIRTUAL_PROMPT230 }231}232 233# Clear PYTHONHOME234if (Test-Path -Path Env:PYTHONHOME) {235 Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME236 Remove-Item -Path Env:PYTHONHOME237}238 239# Add the venv to the PATH240Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH241$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"242 