【问题标题】:Python argparse set 1 or more parameters to an argumentPython argparse 为参数设置 1 个或多个参数
【发布时间】:2021-06-01 07:41:26
【问题描述】:

所以基本上我确实坐在我的代码上使用 argparse 框架,但我确实有一个问题,我不知道如何实现。

基本上我有多个函数保存到一个字典中,所以我可以通过键调用它,并且这些函数有多个参数(以及更多参数)

所以所有东西的输入都在我注释掉的代码的最后一行,应该像这样运行:

结果应该是 Key() 的名称和解析为参数的值(VALUE1、VALUE2.......)

#filename: testfiler.py
import argparse

def filterOne(par1):
    print(par1)

def filterTwo(par1,par2):
    print(par1,par2)

def filterThree(par1,par2,par3):
    print(par1,par2,par3)

#.... more functions to come

filters = {
    "filterOneKey": filterOne,
    "filterTwoKey": filterTwo,
    "filterThreeKey": filterThree
}

parser = argparse.ArgumentParser()
parser.add_argument('--filter', choices= (list(filters.keys()))) 
parser.add_argument('--filteragrument',metavar='Value',nargs='+') #not sure if it is correct

args = parser.parse_args()
filter = args.filter(args.filteragrument) #not sure if it is correct

print(filter) #show key() ✔️, but need to show the parameter which are parsed into filterargument (Value1,Value2....) 


#should RUN like this:
#python Tool/testfilter.py --filter filterTwoKey --filterargument Value1=23,Value2=55

【问题讨论】:

    标签: python function dictionary parameters argparse


    【解决方案1】:

    您需要做的就是通过filter 参数获取函数,并使用filter_arguments 调用它(请注意,我修正了一个错字,更改了参数名称以遵循约定并删除了metavar '不需要它)

    parser = argparse.ArgumentParser()
    parser.add_argument('--filter', choices=list(filters.keys()))
    parser.add_argument('--filter-arguments', nargs='+')
    
    args = parser.parse_args()
    filters[args.filter](*args.filter_arguments)
    

    然后就可以执行了

    $ python test.py --filter filterOneKey --filter-arguments a
    a
    
    $ python test.py --filter filterTwoKey --filter-arguments a b
    a b
    
    $ python test.py --filter filterThreeKey --filter-arguments a b c
    a b c
    

    当然,您应该使用防御性编程来考虑使用不在字典中的函数名称(使用try-except.get)执行脚本的情况,或者提供参数数量的情况与提供的函数名称不匹配(带有try-except*args)。

    【讨论】:

    • 天啊!!!!!!非常非常感谢您首先提供非常快速的答案,然后帮助我解决问题,我整天都在为这个错误而苦苦挣扎。我确实有一个问题,为什么 - filter-argument 和 filter_argument ?它是在文档中的某个地方写的吗?
    • 我完全不明白你所说的 try-except or.get 是什么意思,因为我对编程很陌生,这对我来说是一个小项目?
    • 我会避免使用可能被解释为彼此缩写的标志。对“--filter-arguments”使用一些简单的东西。
    猜你喜欢
    • 2020-03-22
    • 2011-07-19
    • 2018-01-22
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 2015-07-25
    • 2011-11-20
    相关资源
    最近更新 更多