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

查看:28
本文介绍了使用 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 xy --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天全站免登陆