For example
from fabric.api import run
def test(flag=False):
if flag is True:
run("echo hoge")
else:
run("echo fuga")
Or write
$ fab -H host test:flag=True
When I try to do something like that
fuga
is output.
The argument passed in Fabric is str.
>>> "True" is True
False
It needs to be converted in some way.
Simply cast.
from fabric.api import run
def test(flag=True):
if bool(flag) is True:
run("echo hoge")
else:
run("echo fuga")
$ fab -H host test:flag=False
fuga
However,
$ fab -H host test:flag=false
I will die. " True "
/ " False "
can be cast to boolean, but"true"
/"false"
cannot be cast
There is such a guy in the standard library.
from distutils.util import strtobool
from fabric.api import run
def __strtobool(arg):
return bool(strtobool(arg))
def test(flag="True"):
flag = __strtobool(flag)
if flag is True:
run("echo hoge")
else:
run("echo fuga")
Write like this. With this, you can use "y", "t", on "and other strings instead of"True"
.
However, if you write def test (flag = True):
or the default argument as boolean type, an error will be thrown out.
Prepare an eclectic plan for that time. By the way, I also try to take an exception in case of a string that cannot be converted to strtobool ().
def __strtobool(arg):
try:
if type(arg) == type(True):
return arg
else:
return bool(strtobool(arg))
except ValueError:
...
It's getting more and more troublesome.