argparse多个可选参数与nargs='?'

2024-09-30 08:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用argparse处理几个可选参数。每个参数也将有一个单独的可选参数。例如,我有一个脚本跑步者.py. 我想打电话跑步者.py--functionals——capacity——performance,我希望它使用我设置的常量值。这部分正在工作。我还希望能够指定参数,例如--functionals test1--performance test2和--capacity test3。现在我不使用const,而是将参数改为具有给定值。对于ex.functionals,应该是test1、performance test2等。在后一种情况下,我得到的结果是:-c:error:argument--performance:not allowed with argument--functionals

解析器的代码如下所示:

def get_parser():
parser = argparse.ArgumentParser(add_help=False)
required_arguments = parser.add_argument_group(title = "required arguments")
test_arguments = parser.add_mutually_exclusive_group()

test_arguments.add_argument( 
    '--capacity',
    nargs='?',
)
test_arguments.add_argument( 
    '--functionals',
    nargs='?',                      
)
test_arguments.add_argument( 
    '--performance',
    nargs='?',
)
return parser

Tags: pytestaddparser参数performanceargparseargument

热门问题