70

通常,一旦 run() 调用返回非零退出代码,Fabric 就会退出。但是,对于某些呼叫,这是意料之中的。例如,PNGOut 在无法压缩文件时返回错误代码 2。

目前我只能通过使用 shell 逻辑(do_something_that_fails || truedo_something_that_fails || do_something_else)来规避这个限制,但我宁愿能够将我的逻辑保留在纯 Python 中(就像 Fabric 的承诺一样)。

有没有办法检查错误代码并对其做出反应,而不是让 Fabric 恐慌和死亡?我仍然想要其他调用的默认行为,所以通过修改环境来改变它的行为似乎不是一个好的选择(据我记得,你只能用它来告诉它警告而不是死掉)。

4

4 回答 4

97

settings您可以通过使用上下文管理器和设置来防止非零退出代码中止warn_only

from fabric.api import settings

with settings(warn_only=True):
    result = run('pngout old.png new.png')
    if result.return_code == 0: 
        do something
    elif result.return_code == 2: 
        do something else 
    else: #print error to user
        print result
        raise SystemExit()

更新:我的答案已经过时了。请参阅下面的评论。

于 2011-05-12T06:58:34.477 回答
29

是的你可以。换个环境就好了abort_exception。例如:

from fabric.api import settings

class FabricException(Exception):
    pass

with settings(abort_exception = FabricException):
    try:
        run(<something that might fail>)
    except FabricException:
        <handle the exception>

上的文档abort_exceptionhere

于 2014-08-13T18:13:22.967 回答
4

显然,弄乱环境就是答案。

fabric.api.settings可以用作上下文管理器 (with with) 以将其应用于单个语句。和调用run()的返回值不仅是 shell 命令的输出,还具有允许对错误做出反应的特殊属性(和)。local()sudo()return_codefailed

我想我正在寻找更接近subprocess.PopenPython 的通常异常处理的行为。

于 2011-02-03T16:40:39.277 回答
2

试试这个

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

command = "your command"
x = run(command, capture=True) # run or local or sudo
if(x.stderr != ""):
    error = "On %s: %s" %(command, x.stderr)
    print error
    print x.return_code # which may be 1 or 2
    # do what you want or
    raise Exception(error) #optional
else:
    print "the output of %s is: %s" %(command, x)
    print x.return_code # which is 0
于 2014-12-09T08:36:55.627 回答