Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 709
Alan Plum Avatar asked Feb 03 '11 16:02

Alan Plum


2 Answers

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.

like image 193
akaihola Avatar answered Sep 20 '22 17:09

akaihola


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.

like image 37
ArtOfWarfare Avatar answered Sep 21 '22 17:09

ArtOfWarfare