argparse:如果设置了标志,则忽略位置参数? [英] argparse: Ignore positional arguments if a flag is set?
问题描述
我想为命令提供 3 个参数:
、 和
正常使用情况下.除了有一个特定的标志
--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
或
py program.py <版本><输入文件><输出文件>
但是,由于始终需要位置参数(因为在 --init
之外的任何其他情况下都需要所有 3 个参数),似乎没有办法干净地获取此语法以及我能想到的所有内容of 将使 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.
到目前为止我的代码:
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 个参数(
).
或
该程序仅使用 --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).
推荐答案
您可以定义自己的操作类:
You can define your own action class:
class init_action(argparse.Action):
def __init__(self, option_strings, dest, **kwargs):
return super().__init__(option_strings, dest, nargs=0, default=argparse.SUPPRESS, **kwargs)
def __call__(self, parser, namespace, values, option_string, **kwargs):
# Do whatever should be done here
parser.exit()
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", action=init_action, help="Foo Init.")
return parser.parse_args()
这篇关于argparse:如果设置了标志,则忽略位置参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!