user423455
user423455

Reputation: 843

New to writing fabric file to install packages

from fabric.api import sudo, put, run

def install():
    run('source /home/user/.virtualenvs/demo/bin/activate')
    run('pip install requests')

if __name__ == '__main__':
    install()
# to run this, do fab fabfile

Q1. I want to install pip in that environment. But after the script ran, requests is not install in the virtualenv. Why?

Q2. I am asked to provide host information (the following is also the log for Q1). If my goal is to run on local, is there a better way to handle this?

No hosts found. Please specify (single) host string for connection: localhost
[localhost] run: source /home/user/.virtualenvs/demo/bin/activate
[localhost] Passphrase for private key: 
[localhost] Login password: 
[localhost] run: pip install requests
[localhost] out: Requirement already satisfied (use --upgrade to upgrade): requests in /usr/local/lib/python2.7/dist-packages
[localhost] out: Requirement already satisfied (use --upgrade to upgrade): certifi>=0.0.7 in /usr/local/lib/python2.7/dist-packages (from requests)
[localhost] out: Requirement already satisfied (use --upgrade to upgrade): oauthlib>=0.1.0,<0.2.0 in /usr/local/lib/python2.7/dist-packages (from requests)
[localhost] out: Requirement already satisfied (use --upgrade to upgrade): chardet>=1.0.0 in /usr/lib/python2.7/dist-packages (from requests)
[localhost] out: Requirement already satisfied (use --upgrade to upgrade): rsa in /usr/local/lib/python2.7/dist-packages (from oauthlib>=0.1.0,<0.2.0->requests)
[localhost] out: Requirement already satisfied (use --upgrade to upgrade): pyasn1>=0.0.13 in /usr/local/lib/python2.7/dist-packages (from rsa->oauthlib>=0.1.0,<0.2.0->requests)
[localhost] out: Cleaning up...
[localhost] out: 

Update

I can install the packages in a single run command. Is there a better way to do that?

Thanks.


Here is the update code:

from fabric.api import sudo, put, run
from fabric.context_managers import prefix

def install():
    with prefix('source /home/user/.virtualenvs/demo/bin/activate'):
        run('pip install requests')

if __name__ == '__main__':
    install()

http://docs.fabfile.org/en/1.2.0/api/core/context_managers.html?highlight=prefix#fabric.context_managers.prefix

Upvotes: 1

Views: 1083

Answers (1)

pyfunc
pyfunc

Reputation: 66729

Each fabric.run command spawns a separate subshell in which the command is executed.

If you activate virtualenv in one of your run commands, the environment is not available for subsequent command execution in a separate invocation of run command.

See the following discussion on stackoverflow for the correct solution:

Checkout the usage of contextmanager to run commands with virtualenv activated.

Upvotes: 2

Related Questions