当命令失败并出错时,获取fabric.local或run或sudo的输出

时间:2014-12-08 16:01:25

标签: linux error-handling output warnings fabric

我使用fabric来运行linux命令以便建立网络api 我想在失败时输出命令并输出错误! 当我做的时候

from fabric.api import local, env

result = local("command", capture = True)

如果命令成功,我得到输出 但如果出现错误,我会收到异常。

当我添加这样的后备时:

result = local("command || echo 'Failed'", capture = True)

我得失败' 我想得到shell命令给出的确切错误。

如果我这样做:

env.warning_only = True
result = local("command")

我可以让程序继续工作,我看到"错误"当我发送失败的请求时,描述为终端上的警告 但我想得到这些"错误"关于我的程序的描述,将它们返回给客户。

使用此代码:

env.warning_only = True
result = local("command")

我只能得到result.return_code,它可以是0(成功)或1或2 当我将capture = True添加到最后一个代码时,我没有得到return_code而且我得到了 仅在命令成功时输出

示例:我有桥牌" br-vxlan55"和vxlan vxlan55,我将vxlan添加到网桥,之后如果用户想要将相同的vxlan添加到同一个网桥,则应该在终端上显示的请求响应中返回错误:

local("sudo brctl addif br-vxlan55 vxlan55")
local("sudo brctl addif br-vxlan55 vxlan55")#AGAIN

终端输出:


设备vxlan55已经是一个桥梁的成员;不能奴役它来桥接br-vxlan55。

警告:local()执行' sudo brctl addif br-vxlan55 vxlan55'

时遇到错误(返回代码1)

我得到1作为retun_code 我想得到" 设备vxlan55已经是一个桥梁的成员;不能奴役它来桥接br-vxlan55。"在我的程序上作为本地的输出。这可能吗?

这只是一个例子,我有许多其他命令可能会失败,我想获取错误描述以将它们作为请求响应返回。

1 个答案:

答案 0 :(得分:2)

我找到了解决方案,它是“stderr”,我不知道它

from fabric.api import local, env
env.warn_only = True # if you want to ignore exceptions and handle them yurself

command = "your command"
x = local(command, capture=True)
if(x.stderr != ""):
    error = "On %s: %s" %(command, x.stderr)
    print x.return_code # which may be 1 or 2
    print error
    raise Exception(error) #optional
else:
    print "the output of %s is: %s" %(command, x)
    print x.return_code # which is 0