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?
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With