下面的函数和用法示例正好说明了这种用法所需的内容:
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.
谢谢你的帮助。
发布于 2013-07-27 21:17:17
查找或编写一个解析字符串的函数,如“True”、“False”。例如,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
的唯一字符串是''
。
发布于 2013-07-25 04:46:29
如果您给参数一个以"-“开头的名称,它将成为标志参数。正如您从“使用”中看到的,它例外地称为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
发布于 2013-07-25 23:51:22
多亏了瓦雷萨,他让我找到了这个解决方案:
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新手),还是有一种更简单、更直截了当、更优雅的方式来做到这一点?一种类似于函数处理它的非常简单的方式的方法,如最初的公告所示。
https://stackoverflow.com/questions/17857965
复制