Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass bool argument to fabric command

Currently I'm using fab -f check_remote.py func:"arg1","arg2"... to run fab remote.

Now I need to send a bool arg, but True/False become a string arg, how to set it as bool type?

like image 405
whi Avatar asked Jul 25 '12 02:07

whi


2 Answers

I'm using this:

from distutils.util import strtobool

def func(arg1="default", arg2=False):
    if arg2:
        arg2 = bool(strtobool(arg2))

So far works for me. it will parse values (ignoring case):

'y', 'yes', 't', 'true', 'on', '1'
'n', 'no', 'f', 'false', 'off', '0'

strtobool returns 0 or 1 that's why bool is needed to convert to True/False boolean.

For completeness, here's strtobool's implementation:

def strtobool (val):
    """Convert a string representation of truth to true (1) or false (0).

    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
    'val' is anything else.
    """
    val = val.lower()
    if val in ('y', 'yes', 't', 'true', 'on', '1'):
        return 1
    elif val in ('n', 'no', 'f', 'false', 'off', '0'):
        return 0
    else:
        raise ValueError("invalid truth value %r" % (val,))

Slightly better version (thanks for comments mVChr)

from distutils.util import strtobool

def _prep_bool_arg(arg): 
    return bool(strtobool(str(arg)))

def func(arg1="default", arg2=False):
    arg2 = _prep_bool_arg(arg2)
like image 184
Engrost Avatar answered Oct 20 '22 11:10

Engrost


I would use a function:

def booleanize(value):
    """Return value as a boolean."""

    true_values = ("yes", "true", "1")
    false_values = ("no", "false", "0")

    if isinstance(value, bool):
        return value

    if value.lower() in true_values:
        return True

    elif value.lower() in false_values:
        return False

    raise TypeError("Cannot booleanize ambiguous value '%s'" % value)

Then in the task:

@task
def mytask(arg):
    arg = booleanize(arg)
like image 37
charlax Avatar answered Oct 20 '22 11:10

charlax