How to ignore command failure when running it using Fabric 2
Asked Answered
S

1

8

In Fabric 1 it looks like this:

with settings(warn_only=True):
    run_commands_that_may_fail()

It is unclear how to implement it in Fabric 2, pyinvoke via context manager. The upgrade docs recommend replacing warn_only with run.warn. I've come up with:

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

Perhaps, there is a nicer way that is similar to Fabric's 1.

Supranational answered 2/6, 2021 at 13:49 Comment(2)
the new method for fabric 2 seems more pythonic (as in: extensive use of try-catch-finally), maybe such change was really the intended behavior?Bartolommeo
Have you considered just making your own context manager to do this?Beet
N
5

As Artemis said, I think a context manager would be best here - unless you're happy to provide the kwarg for every specific call. For example:

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

Concerning the context manager, you could create a whole new config so you don't have to modify the original:

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)
Nonesuch answered 5/11, 2021 at 11:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.