You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Activate.ps1 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. <#
  2. .Synopsis
  3. Activate a Python virtual environment for the current Powershell session.
  4. .Description
  5. Pushes the python executable for a virtual environment to the front of the
  6. $Env:PATH environment variable and sets the prompt to signify that you are
  7. in a Python virtual environment. Makes use of the command line switches as
  8. well as the `pyvenv.cfg` file values present in the virtual environment.
  9. .Parameter VenvDir
  10. Path to the directory that contains the virtual environment to activate. The
  11. default value for this is the parent of the directory that the Activate.ps1
  12. script is located within.
  13. .Parameter Prompt
  14. The prompt prefix to display when this virtual environment is activated. By
  15. default, this prompt is the name of the virtual environment folder (VenvDir)
  16. surrounded by parentheses and followed by a single space (ie. '(.venv) ').
  17. .Example
  18. Activate.ps1
  19. Activates the Python virtual environment that contains the Activate.ps1 script.
  20. .Example
  21. Activate.ps1 -Verbose
  22. Activates the Python virtual environment that contains the Activate.ps1 script,
  23. and shows extra information about the activation as it executes.
  24. .Example
  25. Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
  26. Activates the Python virtual environment located in the specified location.
  27. .Example
  28. Activate.ps1 -Prompt "MyPython"
  29. Activates the Python virtual environment that contains the Activate.ps1 script,
  30. and prefixes the current prompt with the specified string (surrounded in
  31. parentheses) while the virtual environment is active.
  32. #>
  33. Param(
  34. [Parameter(Mandatory = $false)]
  35. [String]
  36. $VenvDir,
  37. [Parameter(Mandatory = $false)]
  38. [String]
  39. $Prompt
  40. )
  41. <# Function declarations --------------------------------------------------- #>
  42. <#
  43. .Synopsis
  44. Remove all shell session elements added by the Activate script, including the
  45. addition of the virtual environment's Python executable from the beginning of
  46. the PATH variable.
  47. .Parameter NonDestructive
  48. If present, do not remove this function from the global namespace for the
  49. session.
  50. #>
  51. function global:deactivate ([switch]$NonDestructive) {
  52. # Revert to original values
  53. # The prior prompt:
  54. if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
  55. Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
  56. Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
  57. }
  58. # The prior PYTHONHOME:
  59. if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
  60. Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
  61. Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
  62. }
  63. # The prior PATH:
  64. if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
  65. Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
  66. Remove-Item -Path Env:_OLD_VIRTUAL_PATH
  67. }
  68. # Just remove the VIRTUAL_ENV altogether:
  69. if (Test-Path -Path Env:VIRTUAL_ENV) {
  70. Remove-Item -Path env:VIRTUAL_ENV
  71. }
  72. # Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
  73. if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
  74. Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
  75. }
  76. # Leave deactivate function in the global namespace if requested:
  77. if (-not $NonDestructive) {
  78. Remove-Item -Path function:deactivate
  79. }
  80. }
  81. <#
  82. .Description
  83. Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
  84. given folder, and returns them in a map.
  85. For each line in the pyvenv.cfg file, if that line can be parsed into exactly
  86. two strings separated by `=` (with any amount of whitespace surrounding the =)
  87. then it is considered a `key = value` line. The left hand string is the key,
  88. the right hand is the value.
  89. If the value starts with a `'` or a `"` then the first and last character is
  90. stripped from the value before being captured.
  91. .Parameter ConfigDir
  92. Path to the directory that contains the `pyvenv.cfg` file.
  93. #>
  94. function Get-PyVenvConfig(
  95. [String]
  96. $ConfigDir
  97. ) {
  98. Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
  99. # Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
  100. $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
  101. # An empty map will be returned if no config file is found.
  102. $pyvenvConfig = @{ }
  103. if ($pyvenvConfigPath) {
  104. Write-Verbose "File exists, parse `key = value` lines"
  105. $pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
  106. $pyvenvConfigContent | ForEach-Object {
  107. $keyval = $PSItem -split "\s*=\s*", 2
  108. if ($keyval[0] -and $keyval[1]) {
  109. $val = $keyval[1]
  110. # Remove extraneous quotations around a string value.
  111. if ("'""".Contains($val.Substring(0,1))) {
  112. $val = $val.Substring(1, $val.Length - 2)
  113. }
  114. $pyvenvConfig[$keyval[0]] = $val
  115. Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
  116. }
  117. }
  118. }
  119. return $pyvenvConfig
  120. }
  121. <# Begin Activate script --------------------------------------------------- #>
  122. # Determine the containing directory of this script
  123. $VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
  124. $VenvExecDir = Get-Item -Path $VenvExecPath
  125. Write-Verbose "Activation script is located in path: '$VenvExecPath'"
  126. Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
  127. Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
  128. # Set values required in priority: CmdLine, ConfigFile, Default
  129. # First, get the location of the virtual environment, it might not be
  130. # VenvExecDir if specified on the command line.
  131. if ($VenvDir) {
  132. Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
  133. } else {
  134. Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
  135. $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
  136. $VenvDir = $VenvDir.Insert($VenvDir.Length, "/")
  137. Write-Verbose "VenvDir=$VenvDir"
  138. }
  139. # Next, read the `pyvenv.cfg` file to determine any required value such
  140. # as `prompt`.
  141. $pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
  142. # Next, set the prompt from the command line, or the config file, or
  143. # just use the name of the virtual environment folder.
  144. if ($Prompt) {
  145. Write-Verbose "Prompt specified as argument, using '$Prompt'"
  146. } else {
  147. Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
  148. if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
  149. Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
  150. $Prompt = $pyvenvCfg['prompt'];
  151. }
  152. else {
  153. Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virutal environment)"
  154. Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
  155. $Prompt = Split-Path -Path $venvDir -Leaf
  156. }
  157. }
  158. Write-Verbose "Prompt = '$Prompt'"
  159. Write-Verbose "VenvDir='$VenvDir'"
  160. # Deactivate any currently active virtual environment, but leave the
  161. # deactivate function in place.
  162. deactivate -nondestructive
  163. # Now set the environment variable VIRTUAL_ENV, used by many tools to determine
  164. # that there is an activated venv.
  165. $env:VIRTUAL_ENV = $VenvDir
  166. if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
  167. Write-Verbose "Setting prompt to '$Prompt'"
  168. # Set the prompt to include the env name
  169. # Make sure _OLD_VIRTUAL_PROMPT is global
  170. function global:_OLD_VIRTUAL_PROMPT { "" }
  171. Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
  172. New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
  173. function global:prompt {
  174. Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
  175. _OLD_VIRTUAL_PROMPT
  176. }
  177. }
  178. # Clear PYTHONHOME
  179. if (Test-Path -Path Env:PYTHONHOME) {
  180. Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
  181. Remove-Item -Path Env:PYTHONHOME
  182. }
  183. # Add the venv to the PATH
  184. Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
  185. $Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"