Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Python Exception Type (Raised in Fabric)

I'm using Fabric to automate, including the task of creating a directory. Here is my fabfile.py:

#!/usr/bin/env python
from fabric.api import *

def init():
    try:
        local('mkdir ./www')
    except ##what exception?##:
        #print exception name to put in above

Run fab fabfile.py and f I already have ./www created an error is raised, but I don't know what kind, so I don't know how to handle the error yet. Fabric only prints out the following:

mkdir: cannot create directory ‘./www’: File exists

Fatal error: local() encountered an error (return code 1) while executing 'mkdir ./www'

Aborting.

What I want to do is be able to find out the error type so that I can except my errors properly without blanket statements. It would be really helpful if an answer does not just tell me how to handle a mkdir exception, but print (or otherwise find the name to) any exception I may run into down the line (mkdir is just an example).

Thank you!

like image 635
mh00h Avatar asked Jul 21 '13 05:07

mh00h


2 Answers

The issue is that fabric uses subprocess for doing these sorts of things. If you look at the source code for local you can see it doesn't actually raise an exception. It calls suprocess.Popen and uses communicate() to read stdout and stderr. If there is a non-zero return code then it returns a call to either warn or abort. The default is abort. So, to do what you want, try this:

def init():
    with settings(warn_only=True):
        local('mkdir ./www')

If you look at the source for abort, it looks like this:

 10 def abort(msg):
 21     from fabric.state import output
 22     if output.aborts:
 23         sys.stderr.write("\nFatal error: %s\n" % str(msg))
 24         sys.stderr.write("\nAborting.\n")
 25     sys.exit(1)

So, the exception would be a SystemExit exception. While you could catch this, the proper way to do it is outlined above using settings.

like image 136
sberry Avatar answered Oct 14 '22 09:10

sberry


It is nothing to handle with exception, it is from the fabric api

try to set the entire script's warn_only setting to be true with

  env.warn_only = True
like image 45
Janith Chinthana Avatar answered Oct 14 '22 09:10

Janith Chinthana