解释(并使用)Fabric local命令的输出

Hug*_*own 6 python fabric

我想使用Fabric命令来设置本地开发环境,作为其中的一部分,我希望能够设置一个git远程.这很好用:

from fabric.api import local

def set_remote():
    """ Set up git remote for pushing to dev."""
    local('git remote add myremote git@myremote.com:myrepo.git')
Run Code Online (Sandbox Code Playgroud)

问题在于第二次运行 - 当本地命令因为远程已经存在而爆炸时.我想通过先检查遥控器是否存在来防止这种情况:

在伪代码中,我想做以下事情:

if 'myremote' in local('git remote'):
    print 'Remote \'myremote\' already exists.'
else:
    local('git remote add myremote git@myremote.com:myrepo.git')
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Sea*_*ira 10

您可以使用settings上下文管理器warn_only:

from fabric.context_managers import settings

with settings(warn_only=True):
    # some command we are all right with having fail
Run Code Online (Sandbox Code Playgroud)

或者,您可以capture在local命令上将关键字arg 设置为True:

if 'myremote' in local('git remote', capture=True):
    print 'Remote \'myremote\' already exists.'
else:
    local('git remote add myremote git@myremote.com:myrepo.git')
Run Code Online (Sandbox Code Playgroud)