当Fabric收到错误时如何继续任务
当我定义一个任务要在多个远程服务器上运行时,如果这个任务在第一台服务器上运行出错了,Fabric就会停止并中断这个任务。但是我希望Fabric能够忽略这个错误,继续在下一台服务器上运行这个任务。我该怎么做呢?
举个例子:
$ fab site1_service_gw
[site1rpt1] Executing task 'site1_service_gw'
[site1fep1] run: echo 'Nm123!@#' | sudo -S route
[site1fep1] err:
[site1fep1] err: We trust you have received the usual lecture from the local System
[site1fep1] err: Administrator. It usually boils down to these three things:
[site1fep1] err:
[site1fep1] err: #1) Respect the privacy of others.
[site1fep1] err: #2) Think before you type.
[site1fep1] err: #3) With great power comes great responsibility.
[site1fep1] err: root's password:
[site1fep1] err: sudo: route: command not found
Fatal error: run() encountered an error (return code 1) while executing 'echo 'Nm123!@#' | sudo -S route '
Aborting.
7 个回答
13
你还可以把整个脚本的警告设置为只显示警告,这样就不会出现错误信息了,方法是使用
def local():
env.warn_only = True
31
从Fabric 1.5开始,有了一个叫做ContextManager的东西,让这个过程变得更简单:
from fabric.api import sudo, warn_only
with warn_only():
sudo('mkdir foo')
更新:我再次确认了在ipython中使用以下代码是有效的。
from fabric.api import local, warn_only
#aborted with SystemExit after 'bad command'
local('bad command'); local('bad command 2')
#executes both commands, printing errors for each
with warn_only():
local('bad command'); local('bad command 2')
148
来自文档的内容:
... Fabric 默认采用“快速失败”的行为模式:如果出现任何问题,比如远程程序返回了一个非零的返回值,或者你的 fabfile 中的 Python 代码遇到了异常,执行会立即停止。
这种行为通常是我们想要的,但也有很多例外情况,所以 Fabric 提供了一个叫做 env.warn_only 的设置,它是一个布尔值。默认情况下,这个值是 False,意味着一旦出现错误,程序会立刻中止。不过,如果在失败时将 env.warn_only 设置为 True,比如使用设置上下文管理器,Fabric 会发出警告信息,但会继续执行后面的操作。
看起来你可以通过使用settings
上下文管理器来精细控制在哪些地方可以忽略错误,像这样:
from fabric.api import settings
sudo('mkdir tmp') # can't fail
with settings(warn_only=True):
sudo('touch tmp/test') # can fail
sudo('rm tmp') # can't fail