如何将* args与argparse一起使用?

时间:2020-07-15 16:35:36

标签: python command-line 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')

请帮助。预先感谢。

2 个答案:

答案 0 :(得分:1)

https://docs.python.org/3/library/argparse.html#the-add-argument-method

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-or-flags。其次是https://docs.python.org/3/library/argparse.html#nargs

答案 1 :(得分:-1)

使用关键字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)