目前我正在使用 fab -f check_remote.py func:"arg1","arg2"...
来运行 fab remote。
现在我需要发送一个bool arg,但是True/False变成了一个字符串arg,如何设置为bool类型?
最佳答案
我正在使用这个:
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 boolean 值。
为了完整起见,这里是 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)
关于python - 如何将 boolean 参数传递给结构命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11641689/