1
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。但是在脚本运行之后,requests 并没有安装在 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

4

1 回答 1

2

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

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

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

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

于 2012-07-05T20:23:57.160 回答