argparse:如果设置了标志,则忽略位置参数? [英] argparse: Ignore positional arguments if a flag is set?
问题描述
我想为命令提供3个参数:< version>
,<输入文件>
和<输出文件>
在正常使用情况下.除了有一个特定的标志-init
,该标志基本上将运行该程序,而无需任何输入和输出文件规范.
I want to provide the command with 3 arguments: <version>
, <input file>
and <output file>
under normal usage. Except there's a specific flag --init
, which will basically run the program without any input and output file specifications required.
因此,理想情况下,我将拥有一个用法如下的命令:
I would therefore ideally have a command which usage is:
py program.py --init
OR
py program.py< version><输入文件><输出文件>
但是,由于总是需要位置参数(因为在除-init
之外的任何其他情况下,所有三个参数都是必需的),因此似乎无法干净地获得此语法,我想的方法是将3个位置参数设置为一个可选标志,如果在未调用-init
的情况下该可选标志不存在,则会引发异常.而且这一切看起来都很丑.
However, since positional arguments are always required (because all 3 are required in any other circumstance than --init
), there seems to be no way to cleanly get this syntax and all I could think of would be to make the 3 positional arguments into an optional flag, raise an exception if the optional flag isn't there when --init
is not called. And that all seems ugly.
到目前为止,我的代码:
My code so far:
def get_args():
parser = argparse.ArgumentParser(description="Tool for FOO-ing a BAR.")
parser.add_argument(dest="version", help="The version.")
parser.add_argument(dest="input", help="The input file.")
parser.add_argument(dest="output", help="The output file.")
parser.add_argument("-i", "--init", dest="init", action="store_true", help="Foo Init.")
return parser.parse_args()
要澄清:
必须指定所有3个参数(< version>< input>< output>
).
或
仅使用-init
标志运行该程序,并且应指定0个参数.
To Clarify:
Either all 3 arguments (<version> <input> <output>
) MUST be specified.
OR
The program is only ran with --init
flag and 0 arguments should be specified.
程序不应该接受带有0、1或2个指定参数的参数(没有-init
标志).
The program should NOT accept with 0, 1 or 2 arguments specified (without the --init
flag).
推荐答案
parser.add_argument has a default parameter (docs) which can be used here for version, input and output parameters. Now you won't need third init param
这篇关于argparse:如果设置了标志,则忽略位置参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!