PythonSelect.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
<#
.SYNOPSIS
Makes the specified Python distribution the active one for the current session.
 
.DESCRIPTION
A Python distribution is considered "active" when its installation and script locations are both in the current PATH
environment variable and are not shadowed by another distribution. When a Python distribution is enabled, the PATH is
scrubbed of any references to any other Python distribution. Then the selected distribution's installation and script
locations are appended to the PATH.
 
The environment changes remain active only for the current session. Once a distribution has been enabled, references in
the PATH to Python locations should NOT be added, removed, or modified. This may interfere with future attempts to
enable different Python environments within the same session.
 
Parameters can be given to select the distribution that should be enabled. These parameters behave exactly like those
passed to Get-PythonDistribution. See the help for Get-PythonDistribution for more information. If no parameters are
given, then this will attempt to enable the latest version of the official Python distribution found on the system.
 
If no distributions are found matching the given parameters or multiple distributions are found, then this will fail.
 
.PARAMETER Company
Selects and activates a distribution whose company matches the given value.
 
.PARAMETER Tag
Selects and activates a distribution whose tag matches the given value.
 
.PARAMETER Version
Selects and activates a distribution whose version matches the given value. This can also be set to "latest", which
causes only the most recent version of those distributions matching the other filter criteria to be activated.
 
.PARAMETER Bitness
Selects and activates a distribution whose bitness matches the given value.
 
.PARAMETER Scope
Selects and activates a distribution whose scope matches the given value.
 
#>

function Enable-Python {
    [CmdletBinding()]
    param(
        [Parameter()]
        [string] $Company,

        [Parameter()]
        [string] $Tag,

        [Parameter()]
        [string] $Version,

        [Parameter()]
        [ValidateSet( "32", "64" )]
        [string] $Bitness,

        [Parameter()]
        [ValidateSet( "System" , "CurrentUser" )]
        [string] $Scope
    )

    $ErrorActionPreference = "Stop"

    # If no selection criteria is given, we'll try to select the latest version of the standard Python distribution.
    if( -not $Company -and -not $Tag -and -not $Version ) {
        Write-Host "No distribution information given. Searching for latest version of the standard Python distribution."
        $Company = "PythonCore"
        $Version = "latest"

        # If no bitness was selected, then we'll try to select the one whose bitness matches the current environment.
        if( -not $Bitness ) {
            $Bitness = if( [System.Environment]::Is64BitProcess ) { "64" } else { "32" }
        }

        # Unless the user is requesting a specific scope, then make sure we search the system scope.
        if( -not $Scope ) {
            $Scope = "System"
        }
    }

    $getArgs = @{}
    if( $Company ) { $getArgs.Company = $Company }
    if( $Tag ) { $getArgs.Tag = $Tag }
    if( $Version ) { $getArgs.Version = $Version }
    if( $Bitness ) { $getArgs.Bitness = $Bitness }
    if( $Scope ) { $getArgs.Scope = $Scope }

    $distributions = Get-PythonDistribution @getArgs
    if( $distributions.Count -eq 0 ) {
        Write-Host "No Python distributions found matching given distribution information."
        throw "Failed to enable Python distribution. No distributions found."
    }

    if( $distributions.Count -gt 1 ) {
        Write-Host "Multiple Python distributions found matching given distribution information:"
        $distributions | Format-Table -Property Company,Tag,Version,Bitness,Scope | Out-Host
        throw "Failed to enable Python distribution. Ambiguous selection."
    }

    # If this is the first invocation of this cmdlet, wipe any Python paths the user may have previously had set.
    if( -not $global:EnablePythonAlreadySet ) {
        Get-PythonDistribution | Clear-PythonInstallPath
        $global:EnablePythonAlreadySet = $true
    }

    $distribution = $distributions[0]
    Write-Host "Python distribution found in $($distribution.InstallPath). Updating PATH."

    if( $global:EnablePythonInstallPath ) {
        Clear-PythonInstallPath -InstallPath $global:EnablePythonInstallPath
    }

    $environmentPaths = $env:Path.Split( [System.IO.Path]::PathSeparator, [System.StringSplitOptions]::None )
    $environmentPaths += @( $distribution.InstallPath, (Join-Path $distribution.InstallPath "Scripts") )
    $env:Path = [string]::Join( [System.IO.Path]::PathSeparator, $environmentPaths )
    $global:EnablePythonInstallPath = $distribution.InstallPath
}
<#
.SYNOPSIS
Gets information on all registered Python distributions installed on the current system.
 
.DESCRIPTION
According to PEP 514 (https://www.python.org/dev/peps/pep-0514/), Python distributions are to register themselves on
Windows using well-defined registry locations. Distributions can either be installed in a system-wide location or in a
user-specific location.
 
Within a given scope, distributions are differentiated by a pair of values denoting what PEP 514 refers to as the
distribution's company and the tag. Each distribution can also be 32- or 64-bit.
 
These identifying pieces of information can be used to discover which Python distributions are available to the user on
the current system. They can also be used to filter the list of available distributions, which is useful for eventually
enabling a particular distribution within the current session.
 
When no arguments are given, information on all registered Python distributions with a valid installation are returned.
The values returned can then be passed to Enable-Python to enable a specific distribution. Passing additional arguments
will filter the list of returned distributions based on the filtered properties.
 
A filter on a distribution property will match a distribution if any of the following conditions are met:
 
  1. The distribution's property matches exactly the filtered value.
  2. The distribution's property is prefixed by the filtered value.
  3. The distribution's property is "like" the filtered value (according to the rules of the -like operator). This means
     the filtered value can contain wildcard characters.
 
All comparisons and checks are done in a case-insensitive manner.
 
.PARAMETER Company
Returns distributions whose company matches the given value.
 
.PARAMETER Tag
Returns distributions whose tag matches the given value.
 
.PARAMETER Version
Returns distributions whose version matches the given value. This can also be set to "latest", which causes only the
most recent version of those distributions matching the other filter criteria to be returned.
 
.PARAMETER Bitness
Returns distributions whose bitness matches the given value.
 
.PARAMETER Scope
Returns distributions whose scope matches the given value.
 
#>

function Get-PythonDistribution {
    [CmdletBinding()]
    param(
        [Parameter()]
        [string] $Company,

        [Parameter()]
        [string] $Tag,

        [Parameter()]
        [string] $Version,

        [Parameter()]
        [ValidateSet( "32", "64" )]
        [string] $Bitness,

        [Parameter()]
        [ValidateSet( "System", "CurrentUser" )]
        [string] $Scope
    )

    $ErrorActionPreference = "Stop"

    $distributions = @()
    $distributionSets = @(
        @{
            RegKeyPrefix = "HKLM:\SOFTWARE\Python"
            Scope = "System"
        },

        @{
            RegKeyPrefix = "HKLM:\SOFTWARE\WOW6432Node\Python"
            Scope = "System"
        }

        @{
            RegKeyPrefix = "HKCU:\Software\Python"
            Scope = "CurrentUser"
        }
    )

    foreach( $distributionSet in $distributionSets ) {
        if( -not $Scope -or $distributionSet.Scope -eq $Scope ) {
            foreach( $companyKey in (Get-ChildItem -Path $distributionSet.RegKeyPrefix -ErrorAction Ignore) ) {
                if( -not $Company -or (Compare-DistributionSelector $companyKey.PSChildName $Company) ) {
                    foreach( $tagKey in (Get-ChildItem -Path $companyKey.PSPath) ) {
                        if( -not $Tag -or (Compare-DistributionSelector $tagKey.PSChildName $Tag) ) {
                            $installPathKey = Get-Item -Path "$($tagKey.PSPath)\InstallPath" -ErrorAction Ignore
                            if( $installPathKey ) {
                                $installPath = Get-ItemPropertyValue -Path $installPathKey.PSPath -Name "(Default)"

                                # If we can't get the distribution version or bitness, this is usually because there is
                                # no Python interpreter installed at the given install path. This would typically happen
                                # if a distribution doesn't properly clean out its registry keys whenever it is removed.
                                $distributionVersion = Get-DistributionVersion -InstallPath $installPath
                                if( -not $distributionVersion ) {
                                    Write-Warning ("Cannot determine distribution version. Skipping distribution " +
                                        "located at install path $installPath (Company=$($companyKey.PSChildName), " +
                                        "Tag=$($tagKey.PSChildName), Scope=$($distributionSet.Scope)).")
                                    continue
                                }

                                if( $Version -and $Version -ne "latest" -and
                                    -not (Compare-DistributionSelector $distributionVersion $Version) ) {
                                    continue
                                }

                                $distributionBitness = Get-DistributionBitness -InstallPath $installPath
                                if( -not $distributionBitness ) {
                                    Write-Warning ("Cannot determine distribution bitness. Skipping distribution " +
                                        "located at install path $installPath (Company=$($companyKey.PSChildName), " +
                                        "Tag=$($tagKey.PSChildName), Scope=$($distributionSet.Scope)).")
                                    continue
                                }

                                if( $Bitness -and -not (Compare-DistributionSelector $distributionBitness $Bitness) ) {
                                    continue
                                }

                                $distributions += [PSCustomObject]@{
                                    Company = $companyKey.PSChildName
                                    Tag = $tagKey.PSChildName
                                    Version = $distributionVersion
                                    Bitness = $distributionBitness
                                    Scope = $distributionSet.Scope
                                    InstallPath = $installPath
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    if( $Version -eq "latest" ) {
        $latestVersion = $distributions | `
            % { [System.Version]$_.Version } | `
            Measure-Object -Maximum | `
            Select-Object -ExpandProperty Maximum

        $distributions = $distributions | ? { $_.Version -eq $latestVersion }
    }

    $distributions
}
<#
.SYNOPSIS
Removes traces of the given installation location to a particular Python distribution from the user's PATH.
 
.DESCRIPTION
This searches for the given installation location as well as $InstallPath\Scripts in the user's PATH environment
variable. If either are found, then they are removed. These changes do not persist beyond the current session in which
they are made.
 
.PARAMETER InstallPath
Root directory of the Python distribution to search for in the user's PATH.
 
#>

function Clear-PythonInstallPath {
    [CmdletBinding()]
    param(
        [Parameter( Mandatory, ValueFromPipelineByPropertyName )]
        [string[]] $InstallPath
    )

    begin {
        $environmentPaths = $env:Path.Split( [System.IO.Path]::PathSeparator, [System.StringSplitOptions]::None )
        $normalizedEnvironmentPaths = $environmentPaths | % { if( $_ ) { Get-NormalizedPath -Path $_ } else { "" } }
        $pathsToRemove = @()
    }

    process {
        foreach( $path in $InstallPath ) {
            $pythonPath = Get-NormalizedPath -Path $path
            $scriptsPath = Get-NormalizedPath -Path (Join-Path $path "Scripts")

            for( $iEnvPath = 0; $iEnvPath -lt $environmentPaths.Count; $iEnvPath++ ) {
                if( $pythonPath -eq $normalizedEnvironmentPaths[$iEnvPath] -or
                    $scriptsPath -eq $normalizedEnvironmentPaths[$iEnvPath] ) {
                    $pathsToRemove += $environmentPaths[$iEnvPath]
                }
            }
        }
    }

    end {
        $environmentPaths = $environmentPaths | ? { $pathsToRemove -notcontains $_ }
        $env:Path = [string]::Join( [System.IO.Path]::PathSeparator, $environmentPaths )
    }
}
<#
.SYNOPSIS
Checks to see if the reference selector matches the given difference selector. Read the description to see what
constitutes a match.
 
.DESCRIPTION
All comparisons are done in a case-insensitive manner. The rules for matching are as follows:
 
  1. If the reference and difference selectors are equal, then the result is true. This is an exact match.
  2. If the difference selector is a prefix of the reference selector, then the result is true. This is a prefix match.
  3. If the reference selector is "like" the difference selector (as determined by the -like operator), then the result
     is true. This is a wildcard match.
  4. In all other cases, the result is false.
 
.PARAMETER Reference
The selector against which the difference selector is compared.
 
.PARAMETER Difference
The selector to compare against the reference selector. This may contain wildcard characters.
 
.EXAMPLE
Perform an exact match.
 
Compare-DistributionSelector -Reference PythonCore -Difference PythonCore
$true
 
.EXAMPLE
Perform a prefix match.
 
Compare-DistributionSelector -Reference 3.6.3 -Difference 3.6
$true
 
.EXAMPLE
Perform a wildcard match.
 
Compare-DistributionSelector -Reference Continuum -Difference "Cont*"
$true
 
#>

function Compare-DistributionSelector {
    [CmdletBinding()]
    param(
        [Parameter( Mandatory )]
        [string] $Reference,

        [Parameter( Mandatory )]
        [string] $Difference
    )

    # First check for exact match. This always trumps everything.
    if( $Reference -eq $Difference ) {
        return $true
    }

    # Now do a prefix match. This is likely the most common type of fuzzy match we'll expect. For example, someone may
    # say they want to enable version 3.6, which will match version 3.6.3.
    if( $Reference.StartsWith( $Difference, [System.StringComparison]::OrdinalIgnoreCase ) ) {
        return $true
    }

    # Lastly we support wildcard matching.
    if( $Reference -like $Difference ) {
        return $true
    }

    $false
}
<#
.SYNOPSIS
Gets whether the Python interpreter installed at the given install location is 32- or 64-bit.
 
.PARAMETER InstallPath
Root directory of the Python distribution to check.
 
#>

function Get-DistributionBitness {
    [CmdletBinding()]
    param(
        [Parameter( Mandatory )]
        [string] $InstallPath
    )

    $python = Get-Python -InstallPath $InstallPath
    if( $python ) {
        & $python -c "import struct; print( 8 * struct.calcsize( 'P' ) )"
    }
}
<#
.SYNOPSIS
Gets the version of the Python interpreter installed at the given install location in major.minor.micro format.
 
.PARAMETER InstallPath
Root directory of the Python distribution to check.
 
#>

function Get-DistributionVersion {
    [CmdletBinding()]
    param(
        [Parameter( Mandatory )]
        [string] $InstallPath
    )

    $python = Get-Python -InstallPath $InstallPath
    if( $python ) {
        # Older versions of Python don't have support for the tuple field names major, minor, and micro. Instead, we
        # access the version info fields by their respective indexes.
        & $python -c "import sys; print( '%d.%d.%d' % (sys.version_info[0], sys.version_info[1], sys.version_info[2]) )"
    }
}
<#
.SYNOPSIS
"Normalizes" a path by ensuring it has exactly one trailing slash.
 
.DESCRIPTION
This is used to make directory path comparisons easier in, e.g,. Clear-PythonInstallPath.
 
.PARAMETER Path
The path to normalize.
 
#>

function Get-NormalizedPath {
    [CmdletBinding()]
    param(
        [Parameter( Mandatory )]
        [string] $Path
    )

    # This is kind of hacky, but it's a way to ensure all the PATH items we care about have a trailing slash for easier
    # install path comparison.
    Join-Path $Path ""
}
<#
.SYNOPSIS
Gets the Python executable installed at the given installation location.
 
.PARAMETER InstallPath
Root directory of the Python distribution to get the executable from.
 
#>

function Get-Python {
    [CmdletBinding()]
    param(
        [Parameter( Mandatory )]
        [string] $InstallPath
    )

    Get-Command (Join-Path $InstallPath "python.exe") -ErrorAction Ignore
}