在argparse中未设置optinal的情况下如何获取两个位置参数 [英] How to take two positional arguments when optinal isn't set in argparse
本文介绍了在argparse中未设置optinal的情况下如何获取两个位置参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我不设置可选参数时,我想编写一个需要两个位置参数的argparse命令.就我而言,这就像我想用两个必要的参数来调用它,但是当我说python3 test.py -gui
时,我希望您不需要这两个参数,因为那样您就在使用gui.
I want to write a argparse command that needs two postional arguments when I don't set a optional argument. In my case it's like I want to call it with two necessary parameters but when I say python3 test.py -gui
I want that you don't need this two arguments, because then you are using the gui.
Thx
推荐答案
这是我在评论中提出的建议:
This is what I was proposing in the comments:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--gui', action='store_true', help="use GUI")
parser.add_argument('args', nargs='*')
cmdargs = parser.parse_args()
nargs = len(cmdargs.args)
nargs_expected = 0 if cmdargs.gui else 2
if nargs != nargs_expected:
parser.error(f"{nargs_expected} arguments were expected, but got {nargs}")
这篇关于在argparse中未设置optinal的情况下如何获取两个位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文