Search code examples
pythonpython-2.7virtualenvzshfabric

Getting a Python Virtual Environment, Fabric and Sudo to Work Together


Steps to reproduce:

  1. In a linux environment, create a folder on your desktop called 'fab'
  2. FYI, I'm using zsh
  3. cd to ~/Desktop/fab
  4. Run this fabfile.py made in your ./fab dir by issuing fab init:

    #!/usr/bin/env python
    #set up ssh to remote server
    
    import sys, os, fileinput
    from fabric.api import *
    
    def init():
        local('mkdir ./virtualenv')
        local('cd ./virtualenv && virtualenv --no-site-packages venv')
        local('chown -R user:user ./virtualenv/')
        local('chmod 770 -R ./virtualenv/')
        venv = 'source ./virtualenv/venv/bin/activate && '
        local(venv+'pip install mysql-python django South')
    
  5. Get this error:

    ➜  fab  fab init    
    [localhost] local: mkdir ./virtualenv
    [localhost] local: cd ./virtualenv && virtualenv --no-site-packages venv
    New python executable in venv/bin/python
    Installing distribute...........................................................................................................................................................................................................................done.
    Installing pip................done.
    [localhost] local: chown -R user:user ./virtualenv/
    [lcalhost] local: chmod 770 -R ./virtualenv/
    [localhost] local: source ./virtualenv/venv/bin/activate && pip install mysql-python django South
    /bin/sh: 1: source: not found
    
    Fatal error: local() encountered an error (return code 127) while executing 'source ./virtualenv/venv/bin/activate && pip install mysql-python django South'
    
    Aborting.
    
  6. Run source ./virtualenv/venv/bin/activate && pip install mysql-python django South from zsh, and observe that it works.

This is not a duplicate question of something like this, as I am getting the same error even if I use a with prefix( in my code.

Any ideas?


Solution

  • Replace source with /bin/bash/. Here's an example:

    from fabric.api import *
    
    
    def init():
        local('virtualenv --no-site-packages venv')
    
        venv_command = '/bin/bash venv/bin/activate'
        pip_command = 'venv/bin/pip install mysql-python django South'
        local(venv_command + ' && ' + pip_command)
    

    FYI, for run/sudo it's better to use prefix context manager, like suggested here.

    Hope that helps.