如何将*args与argparse结合使用



我正在尝试使用argparse模块来解析命令行参数,并且我希望使用*args,因为参数的数量不是固定的。

我的代码:

if __name__ == '__main__':

parser = argparse.ArgumentParser()
parser.add_argument("program", help='Name of the program')
parser.add_argument("type", help='Type of program')
parser.add_argument("date", help='Date of the file')

这3个参数是必须的:程序、类型和日期。但是,下一个参数是可选的(有时是必需的,有时不是(。所以,我想在其他参数中使用*args,但我不确定使用argsparse是如何做到的。

可选参数如下所示:

if __name__ == '__main__':

parser = argparse.ArgumentParser()
parser.add_argument("program", help='Name of the program')
parser.add_argument("type", help='Type of program')
parser.add_argument("date", help='Date of the file')
#below arguments are optinal. Hence, I may need to pass all of them in one scenario, or just 1-2 in 
another scenario.
parser.add_argument("option1", help='optinal 1')
parser.add_argument("option2", help='optinal 2')
parser.add_argument("option3", help='optinal 3')
parser.add_argument("option4", help='optinal 4')

请帮忙。提前谢谢。

https://docs.python.org/3/library/argparse.html#the-添加自变量方法

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

name of flags*args自变量;可以为positional指定一个名称,也可以为optional指定多个名称(例如"('-f','-foo','-foobar',…(

其他参数作为**kwargs接收,因此通常与help参数一样提供。

由于有很多可能的参数,我建议从最简单的开始,然后进行实验。

最重要的是https://docs.python.org/3/library/argparse.html#name-或标志。其次https://docs.python.org/3/library/argparse.html#nargs.

使用关键字required=bool

parser = argparse.ArgumentParser()
parser.add_argument("-p","--program", help='Name of the program', required=True)
parser.add_argument("-f", "--foo", help='Foo', required=False)

最新更新