使用 Fabric 2 运行命令时如何忽略命令失败

jfs*_*jfs 7 python fabric

Fabric 1中,它看起来像这样:

with settings(warn_only=True):
    run_commands_that_may_fail()
Run Code Online (Sandbox Code Playgroud)

目前还不清楚如何在Fabric 2中通过上下文管理器pyinvoke实现它。升级文档建议替换warn_onlyrun.warn. 我想出了:

old_warn = c.config.run.warn
c.config.run.warn = True
try:
    run_commands_that_may_fail(c)
finally:
    c.config.run.warn = old_warn
Run Code Online (Sandbox Code Playgroud)

也许,有一种更好的方法,类似于 Fabric 的 1。

wil*_*pwa 5

正如Artemis所说,我认为上下文管理器在这里是最好的 - 除非您乐意为每个特定调用提供 kwarg。例如:

if c.run('test -f /opt/mydata/myfile', warn=True).failed:
    c.put('myfiles.tgz', '/opt/mydata')
Run Code Online (Sandbox Code Playgroud)

关于上下文管理器,您可以创建一个全新的配置,这样您就不必修改原始配置:

import contextlib

import fabric

config = fabric.Config()
# set options


@contextlib.contextmanager
def run_with_warnings(old_config):
    new_config = old_config.clone()
    new_config.config.run.warn = True
    yield new_config


with run_with_warnings(config) as config_allowing_warning:
    run_commands_that_may_fail(config_allowing_warning)
Run Code Online (Sandbox Code Playgroud)