Skip to main content
  1. Posts/

Python virtual envs

·2 mins

A simple function to bootstrap Python virtualenvs in Powershell. Add it to your profile and then call it as:

create_virtualenv c:\temp\myvirtualenv

Script is here:

function create_virtualenv([string] $virtualenv_path)
{
    #  I assume that python and 7z are on your path.
    $python = "python.exe"
    $z = "7z.exe"
    $temp_dir="C:\temp"

    if (-not(Test-Path $temp_dir)) {
        mkdir $temp_dir
    }

    #  For some reason 7zip doesn't like the path that comes from $env:TEMP
    $downloaded_archive = $temp_dir + "\virtualenv.tar.gz"
    $temp_virtualenv = $temp_dir + "\temporary_virtualenv"
    $url = "https://github.com/pypa/virtualenv/tarball/develop"

    #  Get virtual env
    Write-Host -fore green "Downloading virtual env from $url"
    $client = new-object System.Net.WebClient
    $client.DownloadFile($url, $downloaded_archive)

    #  Unzip it
    Write-Host -fore green "Unzipping $downloaded_archive"
    & "$z" x -y -o$temp_dir $downloaded_archive > $null

    #  Extract tar
    $tarfile = $downloaded_archive -replace '.gz', ''
    if (-not(Test-Path $tarfile)) {
        Write-Host -fore red "Failed to extract to $tarfile"
        return 1
    }
    Write-Host -fore green "Extacting from tarball $tarfile into $temp_virtualenv"
    $output = "-o" + $temp_virtualenv
    & "$z" x -y $tarfile $output > $null

    if (-not(Test-Path $temp_virtualenv)) {
        Write-Host -fore red "Failed to extract to $temp_virtualenv"
        return 1
    }

    #  Find the virtual env python script in the temporary virtual env we downloaded
    $search_for = "virtualenv.py"
    $virtualenv = (Get-ChildItem -Path $temp_virtualenv -Filter $search_for -Recurse).FullName

    if (-not(Test-Path $virtualenv)) {
        Write-Host -fore red "Could not find the virtual env script $virtualenv"
        return
    }

    Write-Host -fore green "Creating virtual env $virtualenv_path"
    if (Test-Path $virtualenv_path) {
        Write-Host -fore yellow "The path $virtualenv_path already exists, deleting it"
        Remove-Item -Force -Recurse $virtualenv_path
    }
    & $python $virtualenv $virtualenv_path

    #  Clean up the temporary virtual env
    Write-Host -fore green "Cleaning up"
    Remove-Item -Force -Recurse $temp_virtualenv
    Write-Host -fore green "Finished - now run the activate script in $virtualenv_path\Scripts"
}