在远程shell中使用Fabric进行run()调用时,是否可以捕获错误代码?

Ala*_*lum 64 python error-handling fabric

通常,只要run()调用返回非零退出代码,Fabric就会退出.但是,对于某些电话,这是预期的.例如,PNGOut在无法压缩文件时返回错误代码2.

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

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

aka*_*ola 90

您可以使用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()
Run Code Online (Sandbox Code Playgroud)

更新:我的答案已过时.见下面的评论.

  • 您甚至不需要检查 return_code,结果的值会根据任务的成功状态评估为布尔值 true 或 false。http://docs.fabfile.org/en/1.7/api/core/operations。 html#fabric.operations.run (2认同)
  • 这对于超时错误不起作用。使用或不使用“使用设置”,甚至尝试/除外,Fabric仍然完全退出。 (2认同)
  • 您也可以使用`result.succeeded`和`result.failed`.要小心直接评估`bool(result)`,因为它使用输出,所以与`hide("warnings")`和类似的东西一起,将无法从失败中获得成功. (2认同)

Art*_*are 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>
Run Code Online (Sandbox Code Playgroud)

文档就abort_exception这里.