【问题标题】:how to parse a boolean argument in a script?如何解析脚本中的布尔参数?
【发布时间】:2013-07-25 08:13:49
【问题描述】:

以下函数和用法示例准确地说明了我对这种用法的需求:

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=True、choices=[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.

感谢您的帮助。

【问题讨论】:

  • 你设置的方式,除了-arg后面的参数,比如:python test.py -arg False。我不熟悉 argparser,但我希望它返回一个字符串(“False”)而不是布尔值(False)

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


【解决方案1】:

如果您给参数一个以“-”开头的名称,它将成为一个标志参数。从“用法”中可以看出,除了它被称为test.py -arg True

如果您不想将-arg 放在参数本身之前,您应该将其命名为arg,这样它将成为一个位置参数。

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

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

如果您希望能够在命令行上键入True 或False,您可能希望将它们保留为字符串并使用if arg == "True"。 argparse 支持布尔参数,但据我所知,它们仅支持以下形式:test.py --arg 导致 arg=true,而仅test.py 将导致 arg=false

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

【讨论】:

    【解决方案2】:

    感谢 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 新手)还是有更简单、更直接、更优雅的方式来做这件事?一种接近于函数处理它的非常直接的方式的方式,如原始帖子所示。

    【讨论】:

      【解决方案3】:

      查找或编写一个解析字符串的函数,例如“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 的唯一字符串是''。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-14
        • 1970-01-01
        • 2011-02-08
        • 1970-01-01
        • 2018-09-12
        • 1970-01-01
        • 2021-12-03
        • 1970-01-01
        相关资源
        最近更新 更多