Python Argparse多次使用相同的参数 [英] Python Argparse use the same argument multiple times

查看:33
本文介绍了Python Argparse多次使用相同的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我遇到了一个问题,所以基本上,我正在使用 Argparse 并希望多次使用相同的参数

Hi guys I am sitting on a problem so basically, I am working with Argparse and want to use the same argument multiple times

--filter 从字典列表过滤器和
中获取一个参数--parameters--filter

--filter takes an argument from the dict list filters and
--parameters pass the parameters for the chosen method from --filter

即:

python filename.py --filter filtermax \
                   --parameter hello 2 \
                   --filter filterPlus \
                   --parameter 6 "hello 9 \
                   --filter printer \
                   --parameter Bye

filters = {
    "filtermax": filtermax, #(2 parameters String,Int)
    "filtermin": filtermin, #(2 parameters String,Int)
    "filterPlus": filterPlus, #(3 parameters Int,String,Int)
    "printer": printer, #(1 parameter String)
    "printer2": printer2 #(1 Parameter String)
}

parser = argparse.ArgumentParser()
parser.add_argument('--filter',choices=list(filters.keys()))
parser.add_argument('--parameter',nargs='+')

args = parser.parse_args()
filt = args.filter
para = args.parameter
data = filters[filt](*para)

推荐答案

如果我正确理解您的问题,您正在寻找的是 add_arguments()action='append'.

If I understand your problem correctly what you are looking for is add_arguments()'s action='append'.

根据文档:

'append' - 存储一个列表,并将每个参数值附加到列表中.这对于允许多次指定一个选项很有用.

'append' - This stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times.

在您的情况下,这将创建 filter 的参数列表和 parameter 的列表列表(将此参数重命名为 参数).

In your case, this will create a list of arguments for filter and a list of lists for parameter (it would make sense to rename this argument to parameters).

您必须稍微调整一下代码并添加检查以查看传入的参数数量是否匹配.

You would have to adapt your code a bit and add a check to see if the number of arguments passed in match.

import argparse

filters = {
    "filtermax": None,
    "filtermin": None,
    "filterPlus": None,
    "printer": None,
    "printer2": None,
}
parser = argparse.ArgumentParser()
parser.add_argument('--filter', choices=filters.keys(), action='append')
parser.add_argument('--parameter', nargs='+', action='append')

args = parser.parse_args()
filt = args.filter
# With `nargs='+'` and `action='append'`
# `args.parameter` becomes a list of lists of strs!
para = args.parameter

if len(filt) != len(para):
    raise SystemExit("Number of arguments for filter and parameter don't match!")

# Assuming your intention is to populate the existing `filters` dict:
for fil, par in zip(filt, para):
    filters[fil] = par

print(filters)

# With the arguments you've specified, the output will look like:
# {
#   'filtermax': ['hello', '2'],
#   'filtermin': None,
#   'filterPlus': ['6', 'hello', '9'],
#   'printer': ['Bye'],
#   'printer2': None
#}

注意:

  • 看起来在您的命令行调用中,有一个无与伦比的单双引号,即 "hello.为此(在 bash 中),您需要删除它或匹配它,即 hello"hello".

    NOTES:

    • It looks like in your command line invocation, there is an unmatched single double-quote, i.e. "hello. For this to work (in bash) you need to remove it or match it, i.e. either hello or "hello".

      在生产类型的环境中,我会添加其他几个检查,例如检查 --parameter--filter 是否都在全部,或使用 required 参数add_argument() 中,如果缺少某些东西,请优雅地退出.

      In a production-type environment, I would add several other checks, for example check if --parameter and --filter have both been specified at all, or use the required argument in add_argument(), and exit gracefully if something is missing.

      即使 add_argument() 有一个 type 参数,您的情况可能太具体而无法使用它.使用上面的解决方案,filters dict 将包含传入 --parameter 的参数作为 lists of <代码>strs.如果您想对传入的参数强制执行特定类型,例如

      Even though add_argument() has a type parameter, your case is probably too specific to make use of it. With the solution above the filters dict will contain the arguments passed in to --parameter as lists of strs. If you want to enforce specific types on the passed in parameters, e.g.

      (3 个参数 Int,String,Int)

      (3 parameters Int,String,Int)

      parse_args() 获取参数后,您需要进行额外的检查.

      you'll need to have additional checks after getting the arguments from parse_args().

      这篇关于Python Argparse多次使用相同的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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