Can I catch error codes when using Fabric to run() calls in a remote shell? Can I catch error codes when using Fabric to run() calls in a remote shell? python python

Can I catch error codes when using Fabric to run() calls in a remote shell?


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

from fabric.api import settingswith 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.


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

from fabric.api import settingsclass FabricException(Exception):    passwith settings(abort_exception = FabricException):    try:        run(<something that might fail>)    except FabricException:        <handle the exception>

The documentation on abort_exception is here.


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.