首页 > 解决方案 > 如何使用列表中的函数参数进行函数调用

问题描述

我想做这样的事情

allowed_args = ['--email', '--password', '--verbose']

if '--email' in allowed_args:
    parser.add_argument('--email')
if '--password' in allowed_args:
    parser.add_argument('--password', help='Better dont use your password on command line')
if '--verbose' in allowed_args:
    parser.add_argument('--verbose', action='store_true')

因为我需要定义,在使用解析参数之前允许哪些参数argparse

这就像 expeted 一样,但是我怎样才能避免使用这些重复的 if 子句(这只是一个例子,我实际上还有更多......)?我想以某种方式预定义参数,然后选择要使用的参数。

标签: pythonargumentsargparse

解决方案


这有点棘手:

allowed_args = {
    '--email':{}, 
    '--password':{'help':'Better dont ...',}, # you can add more items
    '--verbose':{'action':'store_true',}
}

然后:

for k,v in allowed_args.items():
    parser.add_argument(k, **v)

allowed_args你可以为你的值( )添加尽可能多的参数the dict inside


推荐阅读