如何解析脚本中的布尔参数?

时间:2013-07-25 12:24:38

标签: python-2.7 boolean command-line-arguments argparse

以下功能和用法示例说明了我对此用法的确切需求:

test([{True | False}])

>>> def test(arg=True):
...     if arg:
...         print "argument is true"
...     else:
...         print "argument is false"
...
>>> test()
argument is true
>>> test(True)
argument is true
>>> test(False)
argument is false
>>> test(1)
argument is true
>>> test(0)
argument is false
>>> test("foo")
argument is true
>>> test("")
argument is false
>>>

现在我想要完全相同的用法和行为,但使用命令行解析,即使用此用法:

python test [{True | False}]

所以我试图用这样的东西来解决这个问题:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-arg",
    help="I want the usage to be [{True | False}] (defaults to True)")
arg = parser.parse_args().arg

if arg:
    print "argument is true"
else:
    print "argument is false"

但我无法弄明白。我尝试了各种选项和选项组合,其中action="store_true"default=Truechoices=[True, False]type=bool但没有任何效果,例如:

$ python test.py -h
usage: test.py [-h] [-arg ARG]

optional arguments:
  -h, --help  show this help message and exit
  -arg ARG    I want the usage to be [{True | False}] (defaults to True)

$ python test.py
argument is true

$ python test.py True
usage: test.py [-h] [-arg ARG]
test.py: error: unrecognized arguments: True

etc.

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

查找或编写一个解析“True”,“False”等字符串的函数。例如 http://www.noah.org/wiki/Python_notes#Parse_Boolean_strings

def ParseBoolean (b):
    # ...
    if len(b) < 1:
        raise ValueError ('Cannot parse empty string into boolean.')
    b = b[0].lower()
    if b == 't' or b == 'y' or b == '1':
        return True
    if b == 'f' or b == 'n' or b == '0':
        return False
    raise ValueError ('Cannot parse string into boolean.')

将此视为int()float()的布尔等价物然后将其用作参数type

p.add_argument('foo',type=ParseBoolean)

bool()不起作用,因为它解释为False的唯一字符串是''

答案 1 :(得分:1)

如果为参数指定一个以“ - ”开头的名称,它将成为一个标志参数。正如您从“使用”中看到的那样,除了它之外,它被称为test.py -arg True

如果您不想在参数本身之前放置-arg,则应将其命名为arg,因此它将成为位置参数。

参考:http://docs.python.org/dev/library/argparse.html#name-or-flags

默认情况下,它会将参数转换为字符串。所以if arg:不起作用。结果与调用if "foo":

的结果相同

如果您希望能够在命令行上键入TrueFalse,您可能希望将它们保留为字符串并使用if arg == "True"。 Argparse支持布尔参数,但据我所知他们只支持表单:test.py --arg结果为arg = true,而只有test.py会导致arg = false

参考:http://docs.python.org/dev/library/argparse.html#type

答案 2 :(得分:1)

感谢varesa让我顺利找到了解决方案:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("arg",
    nargs="?",
    default="True",
    help="I want the usage to be [{True | False}] (defaults to True)")
arg = parser.parse_args().arg

if arg == "True":
    arg = True
elif arg == "False":
    arg = False
else:
    try:
        arg = float(arg)
        if arg == 0.:
            arg = True
        else:
            arg = False
    except:
        if len(arg) > 0:
            arg = True
        else:
            arg = False

if arg:
    print "argument is true"
else:
    print "argument is false"

然而,在我看来相当复杂。我是愚蠢的(我是Python新手)还是可以有更简单,更直接,更优雅的方式来做到这一点?一种接近函数处理它的非常直接的方式,如原始帖子所示。

相关问题