Activate.ps1 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. .Notes
  33. On Windows, it may be required to enable this Activate.ps1 script by setting the
  34. execution policy for the user. You can do this by issuing the following PowerShell
  35. command:
  36. PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
  37. For more information on Execution Policies:
  38. https://go.microsoft.com/fwlink/?LinkID=135170
  39. #>
  40. Param(
  41. [Parameter(Mandatory = $false)]
  42. [String]
  43. $VenvDir,
  44. [Parameter(Mandatory = $false)]
  45. [String]
  46. $Prompt
  47. )
  48. <# Function declarations --------------------------------------------------- #>
  49. <#
  50. .Synopsis
  51. Remove all shell session elements added by the Activate script, including the
  52. addition of the virtual environment's Python executable from the beginning of
  53. the PATH variable.
  54. .Parameter NonDestructive
  55. If present, do not remove this function from the global namespace for the
  56. session.
  57. #>
  58. function global:deactivate ([switch]$NonDestructive) {
  59. # Revert to original values
  60. # The prior prompt:
  61. if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
  62. Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
  63. Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
  64. }
  65. # The prior PYTHONHOME:
  66. if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
  67. Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
  68. Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
  69. }
  70. # The prior PATH:
  71. if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
  72. Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
  73. Remove-Item -Path Env:_OLD_VIRTUAL_PATH
  74. }
  75. # Just remove the VIRTUAL_ENV altogether:
  76. if (Test-Path -Path Env:VIRTUAL_ENV) {
  77. Remove-Item -Path env:VIRTUAL_ENV
  78. }
  79. # Just remove VIRTUAL_ENV_PROMPT altogether.
  80. if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) {
  81. Remove-Item -Path env:VIRTUAL_ENV_PROMPT
  82. }
  83. # Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
  84. if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
  85. Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
  86. }
  87. # Leave deactivate function in the global namespace if requested:
  88. if (-not $NonDestructive) {
  89. Remove-Item -Path function:deactivate
  90. }
  91. }
  92. <#
  93. .Description
  94. Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
  95. given folder, and returns them in a map.
  96. For each line in the pyvenv.cfg file, if that line can be parsed into exactly
  97. two strings separated by `=` (with any amount of whitespace surrounding the =)
  98. then it is considered a `key = value` line. The left hand string is the key,
  99. the right hand is the value.
  100. If the value starts with a `'` or a `"` then the first and last character is
  101. stripped from the value before being captured.
  102. .Parameter ConfigDir
  103. Path to the directory that contains the `pyvenv.cfg` file.
  104. #>
  105. function Get-PyVenvConfig(
  106. [String]
  107. $ConfigDir
  108. ) {
  109. Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
  110. # Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
  111. $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
  112. # An empty map will be returned if no config file is found.
  113. $pyvenvConfig = @{ }
  114. if ($pyvenvConfigPath) {
  115. Write-Verbose "File exists, parse `key = value` lines"
  116. $pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
  117. $pyvenvConfigContent | ForEach-Object {
  118. $keyval = $PSItem -split "\s*=\s*", 2
  119. if ($keyval[0] -and $keyval[1]) {
  120. $val = $keyval[1]
  121. # Remove extraneous quotations around a string value.
  122. if ("'""".Contains($val.Substring(0, 1))) {
  123. $val = $val.Substring(1, $val.Length - 2)
  124. }
  125. $pyvenvConfig[$keyval[0]] = $val
  126. Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
  127. }
  128. }
  129. }
  130. return $pyvenvConfig
  131. }
  132. <# Begin Activate script --------------------------------------------------- #>
  133. # Determine the containing directory of this script
  134. $VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
  135. $VenvExecDir = Get-Item -Path $VenvExecPath
  136. Write-Verbose "Activation script is located in path: '$VenvExecPath'"
  137. Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
  138. Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
  139. # Set values required in priority: CmdLine, ConfigFile, Default
  140. # First, get the location of the virtual environment, it might not be
  141. # VenvExecDir if specified on the command line.
  142. if ($VenvDir) {
  143. Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
  144. }
  145. else {
  146. Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
  147. $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
  148. Write-Verbose "VenvDir=$VenvDir"
  149. }
  150. # Next, read the `pyvenv.cfg` file to determine any required value such
  151. # as `prompt`.
  152. $pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
  153. # Next, set the prompt from the command line, or the config file, or
  154. # just use the name of the virtual environment folder.
  155. if ($Prompt) {
  156. Write-Verbose "Prompt specified as argument, using '$Prompt'"
  157. }
  158. else {
  159. Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
  160. if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
  161. Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
  162. $Prompt = $pyvenvCfg['prompt'];
  163. }
  164. else {
  165. Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"
  166. Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
  167. $Prompt = Split-Path -Path $venvDir -Leaf
  168. }
  169. }
  170. Write-Verbose "Prompt = '$Prompt'"
  171. Write-Verbose "VenvDir='$VenvDir'"
  172. # Deactivate any currently active virtual environment, but leave the
  173. # deactivate function in place.
  174. deactivate -nondestructive
  175. # Now set the environment variable VIRTUAL_ENV, used by many tools to determine
  176. # that there is an activated venv.
  177. $env:VIRTUAL_ENV = $VenvDir
  178. if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
  179. Write-Verbose "Setting prompt to '$Prompt'"
  180. # Set the prompt to include the env name
  181. # Make sure _OLD_VIRTUAL_PROMPT is global
  182. function global:_OLD_VIRTUAL_PROMPT { "" }
  183. Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
  184. New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
  185. function global:prompt {
  186. Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
  187. _OLD_VIRTUAL_PROMPT
  188. }
  189. $env:VIRTUAL_ENV_PROMPT = $Prompt
  190. }
  191. # Clear PYTHONHOME
  192. if (Test-Path -Path Env:PYTHONHOME) {
  193. Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
  194. Remove-Item -Path Env:PYTHONHOME
  195. }
  196. # Add the venv to the PATH
  197. Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
  198. $Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"