参数的 argparse 可选值 [英] argparse optional value for argument
问题描述
我想区分这三种情况:
- 该标志根本不存在
python example.py
; - 标志存在但没有值
python example.py -t
;和 - 该标志存在并具有值
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.
推荐答案
您可以使用 nargs='?'
:
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.
你的三个案例会给出:
默认
值;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屋!