当Fabric接收到

2024-05-18 11:17:00 发布

您现在位置:Python中文网/ 问答频道 /正文

当我定义要在多个远程服务器上运行的任务时,如果该任务在服务器1上运行并因错误而退出,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.

Tags: therunecho服务器you错误servicesudo
3条回答

来自the docs

... Fabric defaults to a “fail-fast” behavior pattern: if anything goes wrong, such as a remote program returning a nonzero return value or your fabfile’s Python code encountering an exception, execution will halt immediately.

This is typically the desired behavior, but there are many exceptions to the rule, so Fabric provides env.warn_only, a Boolean setting. It defaults to False, meaning an error condition will result in the program aborting immediately. However, if env.warn_only is set to True at the time of failure – with, say, the settings context manager – Fabric will emit a warning message but continue executing.

看起来您可以使用^{} context manager对忽略错误的位置进行细粒度控制,如下所示:

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

从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')

也可以将整个脚本的“仅警告”设置设置为true

def local():
    env.warn_only = True

相关问题 更多 >