Search code examples
pythondjangovirtualenvfabricvirtualenvwrapper

I am unable to switch virtualenv with virtualenvwrapper in Fabric


I am using virtualenvwrapper to use virtualenv for my Django deployement. Following is my Fabric task:

proj_path = '/path/to/proj'

def setup_code():
    sudo('pip install virtualenvwrapper')
    run('export WORKON_HOME=$HOME/.virtualenvs')
    run('source /usr/local/bin/virtualenvwrapper.sh && mkvirtualenv myenv')
    run('source /usr/local/bin/virtualenvwrapper.sh && workon myenv')
    cd(proj_path)
    req_file = os.path.join(proj_path, 'requirements.txt')
    run('pip install -r %s' % req_file)

I executed the above fab task, but it's behaving strangely. pip starts retrieving all the packages, and then starts to execute the setup file for them. While executing setup file it crashes saying Permission denied.

But why? It's working inside ~ and virtualenv.

What am I doing wrong?


Solution

  • Figured out the problem :

    For Fabric :

    cd('dir') # doesn't works.
    

    Following works:

    with cd('dir'):
        print('pwd') # Directory change reflects here.
    

    Similarly, other environmental things like :

    run('export WORKON_HOME=$HOME/.virtualenvs')
    run('source /usr/local/bin/virtualenvwrapper.sh && mkvirtualenv myenv')
    run('source /usr/local/bin/virtualenvwrapper.sh && workon myenv')
    

    But changed to :

    with prefix('WORKON_HOME=$HOME/.virtualenvs'):
        with prefix('source /usr/local/bin/virtualenvwrapper.sh'):
            with prefix('workon myenv'): # Assuming there is a env called `myenv`
                run('pip install -r requirements.txt') # Works in virtualenv
    

    Figured it out from the official documentation : http://docs.fabfile.org/en/stable/api/core/context_managers.html