【发布时间】: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