编写Fabric文件以安装包的新手

时间:2012-07-05 20:03:15

标签: python fabric

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。 我想在那个环境中安装pip。但是在脚本运行之后,请求不会安装在virtualenv中。为什么呢?

Q2。我被要求提供主机信息(以下也是Q1的日志)。如果我的目标是在本地运行,有没有更好的方法来处理这个?

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: 

更新

我可以在一个run命令中安装软件包。有没有更好的方法呢?

感谢。


以下是更新代码:

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

1 个答案:

答案 0 :(得分:2)

每个fabric.run命令都会生成一个单独的子shell,在该子shell中执行命令。

如果在其中一个运行命令中激活virtualenv,则在单独调用run命令时,该环境不可用于后续命令执行。

请参阅有关正确解决方案的stackoverflow的以下讨论:

检查contextmanager的用法,以便在激活virtualenv的情况下运行命令。