使用python argparse支持任意数量的相关命名参数 [英] Support arbitrary number of related named arguments with Python argparse

查看:162
本文介绍了使用python argparse支持任意数量的相关命名参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想支持一个命令行界面,用户可以在其中声明任意数量的样本,每个样本对应一个或多个输入文件.像这样:

I'd like to support a command line interface where users can declare an arbitrary number of samples, with one or more input files corresponding to each sample. Something like this:

$ myprogram.py \
      --foo bar \
      --sample1 input1.tsv \
      --sample2 input2a.tsv input2b.tsv input2c.tsv \
      --sample3 input3-filtered.tsv \
      --out output.tsv

这个想法是选项键将匹配模式--sample(\d+),每个键将使用所有后续参数作为选项值,直到遇到下一个---前缀标志.对于显式声明的参数,这是argparse模块支持nargs='+'选项的常见用例.但是由于我需要支持任意数量的参数,因此无法明确声明它们.

The idea is that the option keys will match the pattern --sample(\d+), and each key will consume all subsequent arguments as option values until the next - or -- prefixed flag is encountered. For explicitly declared arguments, this is a common use case that the argparse module supports with the nargs='+' option. But since I need to support an arbitrary number of arguments I can't declare them explicitly.

parse_known_args命令将使我可以访问所有用户提供的参数,但是未明确声明的参数将不会分组为索引数据结构.对于这些,我需要仔细检查参数列表,向前看,看看有多少后续值对应于当前标志,等等.

The parse_known_args command will give me access to all user-supplied arguments, but those not explicitly declared will not be grouped into an indexed data structure. For these I would need to carefully examine the argument list, look ahead to see how many of the subsequent values correspond to the current flag, etc.

有什么方法可以解析这些选项,而不必从头开始(几乎)重新实现参数解析器的大部分?

Is there any way I can parse these options without having to essentially re-implement large parts of an argument parser (almost) from scratch?

推荐答案

如果您可以使用略有不同的语法,即:

If you can live with a slightly different syntax, namely:

$ myprogram.py \
  --foo bar \
  --sample input1.tsv \
  --sample input2a.tsv input2b.tsv input2c.tsv \
  --sample input3-filtered.tsv \
  --out output.tsv

如果参数名称不包含数字,但仍可以进行分组,请尝试以下操作:

where the parameter name doesn't contain a number, but still it performs grouping, try this:

parser.add_argument('--sample', action='append', nargs='+')

它产生一个列表列表,即. --sample x y --sample 1 2将产生Namespace(sample=[['x', 'y'], ['1', '2']])

It produces a list of lists, ie. --sample x y --sample 1 2 will produce Namespace(sample=[['x', 'y'], ['1', '2']])

这篇关于使用python argparse支持任意数量的相关命名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆