Python 3 argparse:如何在一个位置参数中接受所有浮点值和字符串列表?

Python 3 argparse: how to accept all float values and a list of strings in one positional argument?

在不描述我的程序真正做什么的情况下,让我讲一个假的用例,这应该足以证明我的预期参数用法。

假设我正在构建一个警报程序(同样,这是一个虚假的用例,所以请不要开始告诉我我们在 Linux/Windows 中有本地警报)。它可以在特定的预定义时间(例如 "morning"、"noon")和给定的分钟数后发出警报。我希望我的命令接受这些用例:

$ python alarm_at.py morning
$ python alarm_at.py noon
$ python alarm_at.py evening
$ python alarm_at.py 1
$ python alarm_at.py 2
$ python alarm_at.py 3
...

约束是我只想为此目的使用一个位置参数。另外,可能还有我需要的其他位置参数,所以应该允许这样的事情:

$ python alarm_at.py loud morning long
$ python alarm_at.py low 3 short

在上面,我为警报声音的响度和长度指定了两个虚构的位置参数。

如果您检查 this,您会发现:

type= can take any callable that takes a single string argument and returns the converted value

>>> def perfect_square(string):
...     value = int(string)
...     sqrt = math.sqrt(value)
...     if sqrt != int(sqrt):
...         msg = "%r is not a perfect square" % string
...         raise argparse.ArgumentTypeError(msg)
...     return value
...
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', type=perfect_square)
>>> parser.parse_args(['9'])
Namespace(foo=9)
>>> parser.parse_args(['7'])
usage: PROG [-h] foo
PROG: error: argument foo: '7' is not a perfect square

所以你可以创建一个函数来接受你想要的值并将其设置为参数类型。 您刚刚以正确的顺序设置了多少个位置参数以及 required 与否都没有关系。