在使用argparse的Python中,如何为一个参数提供可变数量的参数?

2024-03-29 15:28:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用argparse向脚本用户建议一个映射选项,如下所示:

parser.add_argument('-m', '--mapping_strategy', 
                    help='mapping strategy', 
                    choices=['ZigZag', 
                    'RoundRobin'])

所以我可以这样使用脚本:

^{pr2}$

我现在需要提供一个新的映射策略,用户可以指定一个自定义文件来描述映射。因此,我现在需要的是:

> script.py -m Custom /home/manu/custom.map

我怎样才能用argparse来实现这一点?在


Tags: 用户脚本addparser选项argparsehelpargument
2条回答

您当然可以使用一个简单的nargs="+",但这有一些缺点, help输出的信息量要少得多。您必须自己验证mapping_strategy[0]是否在['ZigZag', 'RoundRobin', 'Custom']中。在

现在,另一种方法是需要一个-p参数作为映射的路径,并要求在mapping_strategy == 'Custom'时设置它。如果他们提供了错误的映射策略,您也可以打印出“忽略-p参数,只有自定义映射策略才需要”警告消息。在

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-m', " mapping_strategy",
                    help='valid strategies: ZigZag, RoundRobin, Custom', 
                    choices=['ZigZag', 
                    'RoundRobin',
                    'Custom']
                    )

parser.add_argument('-p', " path",
                    help='path to custom map file, required '
                         'if using Custom mapping_strategy', 
                    )

args = parser.parse_args()
if args.mapping_strategy == 'Custom' and args.path == None:
    parser.error('Custom mapping strategy requires a path')
if args.mapping_strategy != 'Custom' and args.path != None:
    print('Ignoring path parameter, only used for Custom mapping_strategy')
print args

也可以使用自定义类来验证参数。这段代码提供了一个更好的帮助消息,以及更好的警告和错误检查。但这有点脆弱,因为我重复了有效的策略列表。但这很容易克服。在

^{pr2}$

以下是帮助输出:

$python mapping_strategy.py -h
usage: mapping_strategy.py [-h] [-m mapping strategy [path to map ...]]

optional arguments:
  -h,  help            show this help message and exit
  -m mapping strategy [path to map ...],  mapping_strategy mapping strategy [path to map ...]
                        valid strategies: ZigZag, RoundRobin, Custom

如果你只提供a-m,会发生以下情况:

$ python mapping_strategy.py -m 
usage: mapping_strategy.py [-h] [-m mapping strategy [path to map ...]]
mapping_strategy.py: error: argument -m/ mapping_strategy: expected at least one argument

如果键入a-m Custom但不提供路径,则可以看到以下内容:

$ python mapping_strategy.py -m Custom
usage: mapping_strategy.py [-h] [-m mapping strategy [path to map ...]]
mapping_strategy.py: error: Custom mapping strategy requires a path

如果给-m之字形并附加一条无意义的路径,会发生以下情况:

$ python mapping_strategy.py -m ZigZag blah blah
path to map only used by Custom mapping strategy
ignoring:  blah blah

如果您提供一个包含空格的路径的自定义选项,您将得到以下结果:

$ python mapping_strategy.py -m Custom c:\My Documents
Namespace(mapping_strategy=['Custom', '"c:My Documents"'])

但是谁会使用Windows,或者在目录名中有空格呢?异教徒。在

如果指定了无效的映射策略,将得到以下结果:

$ python mapping_strategy.py -m Foo
usage: mapping_strategy.py [-h] [-m mapping strategy [path to map ...]]
mapping_strategy.py: error: Invalid mapping strategy Foo

将您的下线改为:

parser.add_argument('-m', ' mapping_strategy', 
                     help='mapping strategy', nargs="+")

这将收集列表中的所有位置参数。如果没有至少一个操作,它也会生成一个错误。在

查看nargs documentation

相关问题 更多 >