There is a much simpler solution! Just go to your python scripts folder, where the workon.bat
file exists and create a new file named workon.ps1
and add the following line to it
iex ("~\Envs\" + $args[0] + "\Scripts\activate.ps1")
You many need to change this appropriately if you store your virtualenvs elsewhere and also set the Execution Policy to allow scripts. Now you can use workon in both cmd and powershell, since the ps1
will be executed in powershell and bat
in cmd.
You can also check out my fork (full disclosure: I'm the author of the powershell part) of virtualenvwrapper-win, which contains some rewritten scripts for powershell and should work on both CMD and powershell. If you want to copy-paste, create two files, workon.ps
and `cdproject.
workon.ps1
:
if (-not (Test-Path env:WORKON_HOME))
{
$WORKON_HOME = '~\Envs'
} else {
$WORKON_HOME = ($env:WORKON_HOME).Replace('"','')
}
if (-not (Test-Path env:VIRTUALENVWRAPPER_PROJECT_FILENAME)) {
$VIRTUALENVWRAPPER_PROJECT_FILENAME = '.project'
} else {
$VIRTUALENVWRAPPER_PROJECT_FILENAME = ($env:VIRTUALENVWRAPPER_PROJECT_FILENAME).Replace('"','')
}
if ($args.length -eq 0) {
echo "Pass a name to activate one of the following virtualenvs:"
echo ==============================================================================
(Get-ChildItem -Path $WORKON_HOME).Name
return
}
$VENV = $args[0]
if (!(Test-Path -Path ("$($WORKON_HOME)\$($VENV)"))) {
echo ("virtualenv $($VENV) does not exist")
echo "Create it with 'mkvirtualenv $($VENV)'"
return
}
if (!(Test-Path -Path ("$($WORKON_HOME)\$($VENV)\Scripts\activate.ps1") )) {
echo "$($WORKON_HOME)$($VENV)"
echo "doesn't contain a virtualenv (yet)."
echo "Create it with 'mkvirtualenv $($VENV)'"
return
}
iex ("$($WORKON_HOME)\$($VENV)\Scripts\activate.ps1")
if (Test-Path -Path ("$($WORKON_HOME)\$($VENV)\$($VIRTUALENVWRAPPER_PROJECT_FILENAME)")) {
iex "cdproject"
}
cdproject.ps1
:
function Show-Usage {
echo ""
echo "switches to the project dir of the activated virtualenv"
}
if (-not (Test-Path env:VIRTUAL_ENV)) {
echo ""
echo "a virtualenv must be activated"
Show-Usage
return
}
if (-not (Test-Path env:VIRTUALENVWRAPPER_PROJECT_FILENAME)) {
$VIRTUALENVWRAPPER_PROJECT_FILENAME = '.project'
} else {
$VIRTUALENVWRAPPER_PROJECT_FILENAME = ($env:VIRTUALENVWRAPPER_PROJECT_FILENAME).Replace('"','')
}
if (-not (Test-Path "$($env:VIRTUAL_ENV)\$($VIRTUALENVWRAPPER_PROJECT_FILENAME)")) {
echo ""
echo "No project directory found for current virtualenv"
Show-Usage
return
}
$ENVPRJDIR = Get-Content "$($env:VIRTUAL_ENV)\$($VIRTUALENVWRAPPER_PROJECT_FILENAME)" -First 1
# If path extracted from file contains env variables, the system will not find the path.
# TODO: Add this functionality
cd $ENVPRJDIR