workon command doesn't work in Windows PowerShell to activate virtualenv workon command doesn't work in Windows PowerShell to activate virtualenv powershell powershell

workon command doesn't work in Windows PowerShell to activate virtualenv


workon is a batch script. If you run it from PowerShell it's launched in a new CMD child process, doing its thing there, then exit and return to the PowerShell prompt. Since child processes can't modify their parent you lose all modifications made by workon.bat when you return to PowerShell.

You basically have two options:

  • Rewrite workon.bat (and the other batch scripts it calls) in PowerShell.

  • Run workon.bat in without exiting from the CMD child process:

    & cmd /k workon <envname>

    If you just want a shortcut workon that you can call directly from PowerShell you can wrap that commandline in a function and put the function definition into your PowerShell profile:

    function workon($environment) {  & cmd /k workon.bat $environment}

    Use the scriptname with extension here to avoid infinite recursion.


The answer by Ansgar Wiechers technically works but it uses cmd which means you are basically using the cmd prompt from within PowerShell and you lose the additional functionality provided by PowerShell. You can modify the function above to the following:

function workon ($env) {        & .\Envs\$env\Scripts\activate.ps1}

This will allow you to continue to use PowerShell commands (that do not work in cmd such as ls) in your virtual environment

This also assumes that your environments are saved in .\Envs. If they are elsewhere, then adjust the path in the function accordingly, or set the WORKON_HOME environment variable, see below.

If you have set the WORKON_HOME environment variable (which you should !), you can instead use:

function workon ($env) {        & $env:WORKON_HOME\$env\Scripts\activate.ps1}

Additionally, if you are not a Windows user (like me) and need help on where to put that function and how to get it to load when you open PowerShell. Here are some additional resources that helped me:

Background:

How to Write a PowerShell Script Module

Importing a PowerShell Module

How to get PowerShell to autoload your module when it starts:

How to Create a PowerShell Profile

Start PowerShell with modules loaded


just type "CMD" on powershell and it will bring up cmd and then workon