【发布时间】:2020-11-05 05:34:25
【问题描述】:
我正在尝试使用 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')
请帮忙。提前致谢。
【问题讨论】:
-
这在一般意义上很难回答,您能提供更多上下文吗?你看过例如
nargs? -
点头;通常,一个人应该使用
nargs='+',或者可能需要这些可选参数的(子)命令的子解析器,或者添加您自己的验证逻辑,当它失败时调用解析器的共享打印错误逻辑。我们真的需要一个更详细的问题才能知道正确的答案是什么。 -
这能回答你的问题吗? Argparse optional positional arguments?
-
您阅读过任何/大部分 argparse 文档吗?注意到关于
positional参数和optionals的任何事情吗?optionals/flagged参数使用类似--option1的名称定义,默认为“可选”。
标签: python command-line argparse