argparse参数的可选值 [英] argparse optional value for argument
问题描述
我想区分这三种情况:
- 该标志根本不存在
python example.py
; - 该标志存在,但没有值
python example.py -t
;和 - 该标志存在并且值为
python example.py -t ~/some/path
.
- The flag is not present at all
python example.py
; - The flag is present but without a value
python example.py -t
; and - The flag is present and has a value
python example.py -t ~/some/path
.
如何使用Python argparse
做到这一点?前两个案例将由action='store_true'
覆盖,但随后第三个案例将变为无效.
How can I do this with Python argparse
? The first two cases would be covered by action='store_true'
but then the third case becomes invalid.
推荐答案
You can do this with nargs='?'
:
如果可能,将从命令行使用一个参数,并且 作为单个项目生产.如果不存在命令行参数,则 将产生默认值.请注意,对于可选参数, 还有另外一种情况-选项字符串存在但不存在 然后是命令行参数.在这种情况下,const的值 将产生.
One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from const will be produced.
您的三种情况将给出:
-
default
值; -
const
值;和 -
'~/some/path'
- The
default
value; - The
const
value; and '~/some/path'
分别.例如,给出以下简单实现:
respectively. For example, given the following simple implementation:
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-t', nargs='?', default='not present', const='present without value')
print(parser.parse_args().t)
您将获得以下输出:
$ python test.py
not present
$ python test.py -t
present without value
$ python test.py -t 'passed a value'
passed a value
这篇关于argparse参数的可选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!