Python argparse - 强制参数 - 位置或可选

2024-02-07

我希望用户能够使用位置参数或可选参数将强制参数传递给“argparse”。

IE。, 以下两种形式均有效:

my_prog arg
my_prog -m arg

我见过Argparse 可选位置参数? https://stackoverflow.com/questions/4480075/argparse-optional-positional-arguments

但那里的建议使both形式可选。我要那个one其中将是强制性的。

当然,我可以在解析后添加手动检查以确保至少其中之一已设置。但我有预感,一定有更好的解决方案。

(即使使用我的手动方法,“帮助”部分也将它们显示为可选)


The mutually exclusive group机制可以采取required范围。它也适用于一个?位置与选项(标记参数)一起。 (多个“?”位置没有意义)。

至于help显示有2个默认组,positonal and optional。所以即使一个optional(标记)设置为required默认情况下,它显示在optional团体。这usageline 可以更好地指导是否需要参数。如果您不喜欢帮助部分中的组标签,请定义您自己的参数组。

In [146]: import argparse
In [147]: parser = argparse.ArgumentParser()
In [148]: gp = parser.add_mutually_exclusive_group(required=True)
In [149]: gp.add_argument('pos', nargs='?', default='foo');
In [150]: gp.add_argument('-f','--foo', default='bar');

In [151]: parser.parse_args('arg'.split())
Out[151]: Namespace(foo='bar', pos='arg')

In [152]: parser.parse_args('-f arg'.split())
Out[152]: Namespace(foo='arg', pos='foo')

In [153]: parser.parse_args('arg -f arg'.split())
usage: ipython3 [-h] [-f FOO] [pos]
ipython3: error: argument -f/--foo: not allowed with argument pos

In [154]: parser.parse_args(''.split())
usage: ipython3 [-h] [-f FOO] [pos]
ipython3: error: one of the arguments pos -f/--foo is required


In [155]: parser.parse_args('-h'.split())
usage: ipython3 [-h] [-f FOO] [pos]

positional arguments:
  pos

optional arguments:
  -h, --help         show this help message and exit
  -f FOO, --foo FOO

哎呀,使用情况没有显示-f and pos在一个相互排斥的群体中。有时候那个usage格式化很脆弱。

切换参数定义的顺序可以提供更好的用法

In [156]: parser = argparse.ArgumentParser()
In [157]: gp = parser.add_mutually_exclusive_group(required=True)
In [158]: gp.add_argument('-f','--foo', default='bar');
In [159]: gp.add_argument('pos', nargs='?', default='foo');
In [160]: 
In [160]: parser.parse_args('-h'.split())
usage: ipython3 [-h] (-f FOO | pos)

positional arguments:
  pos

optional arguments:
  -h, --help         show this help message and exit
  -f FOO, --foo FOO

使用用户定义的参数组:

In [165]: parser = argparse.ArgumentParser()
In [166]: gp = parser.add_argument_group('Mutually exclusive')
In [167]: gpm = gp.add_mutually_exclusive_group(required=True)
In [168]: gpm.add_argument('-f','--foo', default='bar');
In [169]: gpm.add_argument('pos', nargs='?', default='foo');
In [170]: 
In [170]: parser.parse_args('-h'.split())
usage: ipython3 [-h] (-f FOO | pos)

optional arguments:
  -h, --help         show this help message and exit

Mutually exclusive:
  -f FOO, --foo FOO
  pos

这是一般规则 argument_groups 和mutual_exclusive_groups 不适合嵌套的一个例外。

m-x-group 不是必需的,用法将使用[]

usage: ipython3 [-h] [-f FOO | pos]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python argparse - 强制参数 - 位置或可选 的相关文章

随机推荐