70

Normally Fabric quits as soon as a run() call returns a non-zero exit code. For some calls, however, this is expected. For example, PNGOut returns an error code of 2 when it is unable to compress a file.

Currently I can only circumvent this limitation by either using shell logic (do_something_that_fails || true or do_something_that_fails || do_something_else), but I'd rather be able to keep my logic in plain Python (as is the Fabric promise).

Is there a way to check for an error code and react to it rather than having Fabric panic and die? I still want the default behaviours for other calls, so changing its behaviour by modifying the environment doesn't seem like a good option (and as far as I recall, you can only use that to tell it to warn instead of dying anyway).

3
  • 2
    Before someone marks this a duplicate: this question is related, but as I said, I want to react to errors, not ignore them.
    – Alan Plum
    Feb 3, 2011 at 16:17
  • The currently accepted answer is dated. Since July 2013, there's been an environment variable that allows you to specify which exception should be raised when an error occurs (the default is a SystemExit, which isn't a descendant of Exception which is why it generally causes your program to crash). See my answer: stackoverflow.com/a/25293275/901641 Sep 15, 2014 at 12:10
  • // , I'm curious how Invoke would handle this. Oct 26, 2016 at 0:44

4 Answers 4

97

You can prevent aborting on non-zero exit codes by using the settings context manager and the warn_only setting:

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()

Update: My answer is outdated. See comments below.

5
  • 2
    You don't even need to check the return_code, the value of result evaluates as boolean true or false depending on the success state of the task.docs.fabfile.org/en/1.7/api/core/… Aug 12, 2013 at 23:09
  • 3
    This doesn't work for timeout errors. With or without the "with settings" or even with a try/except, Fabric still exits completely.
    – Cerin
    Jul 16, 2014 at 23:38
  • -1: This answer is dated - since July 2013 it's been possible to specify which exception is called when an error is called. See my answer here: stackoverflow.com/a/25293275/901641 Sep 15, 2014 at 12:11
  • I fixed the Python indentation, but now I can't remove the extra text I added to get the edit to apply. Nov 11, 2015 at 18:11
  • 3
    You can alse use result.succeeded and result.failed. Beware of evaluating directly bool(result) because it uses the output, so in conjunction with hide("warnings") and similar, will not be able to tell a success from a failure.
    – rewritten
    Jan 22, 2016 at 10:27
29

Yes, you can. Just change the environment's abort_exception. For example:

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>

The documentation on abort_exception is here.

2
  • 1
    This doesn't seem to provide access to the command's exit code, though.
    – Alan Plum
    Sep 25, 2014 at 14:08
  • @AlanPlum - You can get the exception message... but you're right, I don't see a way of getting the exit code. Feb 29, 2016 at 14:29
4

Apparently messing with the environment is the answer.

fabric.api.settings can be used as a context manager (with with) to apply it to individual statements. The return value of run(), local() and sudo() calls isn't just the output of the shell command, but also has special properties (return_code and failed) that allow reacting to the errors.

I guess I was looking for something closer to the behaviour of subprocess.Popen or Python's usual exception handling.

2

try this

from fabric.api import run, env
env.warn_only = True # if you want to ignore exceptions and handle them yurself

command = "your command"
x = run(command, capture=True) # run or local or sudo
if(x.stderr != ""):
    error = "On %s: %s" %(command, x.stderr)
    print error
    print x.return_code # which may be 1 or 2
    # do what you want or
    raise Exception(error) #optional
else:
    print "the output of %s is: %s" %(command, x)
    print x.return_code # which is 0
2
  • 3
    I tried the above with the following result: TypeError: run() got an unexpected keyword argument 'capture' with Fabric 1.10.2 and Paramiko 1.15.2.
    – dmmfll
    Aug 18, 2015 at 15:28
  • capture=True works only for local(command, capture=True)
    – Kurohige
    Oct 27, 2020 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.