Skip to content

Instantly share code, notes, and snippets.

@pfmoore
Created September 18, 2014 21:57
Show Gist options
  • Select an option

  • Save pfmoore/21d3450bb413a8713053 to your computer and use it in GitHub Desktop.

Select an option

Save pfmoore/21d3450bb413a8713053 to your computer and use it in GitHub Desktop.
Powershell implementation of vex (virtualenv manager)
[CmdletBinding(DefaultParameterSetName="ByName")]
Param (
[Parameter(Position=0, Mandatory=$true, ParameterSetName="ByName")]
[String]
$VE,
[Parameter(Position=1)]
[ScriptBlock]$sb,
[Parameter(Mandatory=$true, ParameterSetName="ByPath")]
[String]
$Path,
[Switch]$Make,
[Switch]$Remove,
[Switch]$Temp,
[String]$CWD
)
# -Path pathname ($ve is $venvroot/$ve)
# -Make creates first
# -Remove removes after
# -Temp creates and removes
# -Cwd changes directory
#
# Not implemented yet
# --venv use python -m venv instead of virtualenv
# --python python executable
# --config config file
#
# If $sb is empty, open a nested prompt
$venvroot = (Resolve-Path "~/.virtualenvs").Path
# A temporary VE is made at start and removed at end
if ($Temp) {
$Make = $true
$Remove = $true
}
# A named VE is stored in $venvroot
if ($PsCmdlet.ParameterSetName -eq "ByName") {
$Path = (Join-Path $venvroot $VE)
}
if ($Make) {
# Make sure the virtualenv does not already exist
if (Test-Path -PathType Container $Path) {
throw "Directory $Path already exists"
}
# If $venvroot doesn't exist, create it
if (($PsCmdlet.ParameterSetName -eq "ByName") -and ! (Test-Path -PathType Container $venvroot)) {
$null = New-Item -Type Directory $venvroot
}
# Make the virtualenv
virtualenv $Path
}
# Check the virtualenv exists
if (! (Test-Path -PathType Container $Path)) {
throw "Virtualenv $Path does not exist"
}
# Work out the full pathname, the Scripts directory and the location of Python
$Path = (Resolve-Path $Path).Path
$scripts = (Join-Path $Path Scripts)
$python = (Join-Path $scripts python.exe)
if (! (Test-Path -PathType Leaf $python)) {
throw "Virtualenv $Path does not exist"
}
$oldpath = $env:PATH
$oldvenv = $env:VIRTUAL_ENV
if ($cwd) { pushd $cwd }
try {
$env:PATH = $scripts + ';' + $env:PATH
$env:VIRTUAL_ENV = $Path
if ($sb) { & $sb } else { $host.EnterNestedPrompt() }
}
finally {
if ($cwd) { popd }
$env:PATH = $oldpath
$env:VIRTUAL_ENV = $oldenv
}
# Remove the virtualenv if requested
if ($Remove) {
Remove-Item -Recurse $Path
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment