如何在Python中使用argparse为一个参数提供可变数量的参数?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何在Python中使用argparse为一个参数提供可变数量的参数?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3787字,纯文字阅读大概需要6分钟。
内容图文
我正在使用argparse为我的脚本用户提出一个映射选项,如下所示:
parser.add_argument('-m', '--mapping_strategy',
help='mapping strategy',
choices=['ZigZag',
'RoundRobin'])
所以我可以这样使用脚本:
> script.py -m ZigZag
我现在需要提供一种新的映射策略,用户可以在其中指定描述映射的自定义文件.因此我现在需要这样的东西:
> script.py -m Custom /home/manu/custom.map
我如何用argparse实现这一点?
解决方法:
你当然可以使用一个简单的nargs =“”,但这有一些缺点, – help输出信息量少得多.你必须自己验证mapping_strategy [0]在[‘ZigZag’,’RoundRobin’,’Custom’]中.
现在,另一种方法是为地图的路径要求-p参数,并要求在mapping_strategy ==’Custom’时设置它.如果它们提供错误的mapping_strategy,您也可以打印出“忽略-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
您也可以使用自定义类来验证参数.此代码提供了更好的帮助消息,以及更好的警告和错误检查.虽然它有点脆弱,因为我复制了valid_strategies列表.但这很容易克服.
import argparse
class ValidateMapping(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
valid_strategies = ('ZigZag', 'RoundRobin', 'Custom')
strategy = values[0]
if strategy not in valid_strategies:
parser.error('Invalid mapping strategy {}'.format(strategy))
if strategy == 'Custom':
if len(values) == 1:
parser.error('Custom mapping strategy requires a path')
elif len(values) == 2:
path = values[1]
elif len(values) > 2:
path = '"' + ' '.join(values[1:]) + '"'
setattr(args, self.dest, [strategy, path])
else:
if len(values) > 1:
print "path to map only used by Custom mapping strategy"
print "ignoring: ",
for i in range(1, len(values)):
print values[i],
print
setattr(args, self.dest, strategy)
parser = argparse.ArgumentParser()
parser.add_argument('-m', "--mapping_strategy",
help='valid strategies: ZigZag, RoundRobin, Custom',
nargs="+",
action=ValidateMapping,
metavar=('mapping strategy', 'path to map')
)
args = parser.parse_args()
print args
这是帮助输出:
$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
如果你只提供一个-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
如果您键入-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 ZigZag并附加一条毫无意义的路径会发生什么:
$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
内容总结
以上是互联网集市为您收集整理的如何在Python中使用argparse为一个参数提供可变数量的参数?全部内容,希望文章能够帮你解决如何在Python中使用argparse为一个参数提供可变数量的参数?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。