目前我正在使用fab -f check_remote.py func:"arg1","arg2"...来运行fab remote。
现在我需要发送一个bool arg,但是True/False变成了一个string arg,怎么设置为bool类型?
发布于 2012-07-25 12:15:59
正如在fabric docs中提到的,所有参数都以字符串的形式结束。这里要做的最简单的事情就是检查参数:
def myfunc(arg1, arg2):
  arg1 = (arg1 == 'True')括号不是必需的,但有助于提高可读性。
编辑:显然我并没有实际尝试我之前的答案;更新。(两年后。)
发布于 2013-10-23 16:31:00
我使用的是:
from distutils.util import strtobool
def func(arg1="default", arg2=False):
    if arg2:
        arg2 = bool(strtobool(arg2))到目前为止对我来说还不错。它将解析值(忽略大小写):
'y', 'yes', 't', 'true', 'on', '1'
'n', 'no', 'f', 'false', 'off', '0'strtobool返回0或1,这就是为什么需要将bool转换为True/False布尔值。
为了完整起见,下面是strtobool的实现:
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,))稍微好一点的版本(感谢评论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)发布于 2013-03-12 06:11:01
我会使用一个函数:
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)然后在任务中:
@task
def mytask(arg):
    arg = booleanize(arg)https://stackoverflow.com/questions/11641689
复制相似问题