我正在学习 argparse 的基础知识,并且我编写了一个在命令行中打印太阳系信息的程序,但是,我使用了 2 个位置参数,这导致了一些复杂性。我的目标是在命令行中输入未知参数时打印“帮助”界面,但由于使用多个位置参数而无法打印。使用可选参数目前是不可能的。
如何打印未知参数的帮助?据我了解,行星不需要被专门称为“行星”,而是任何东西和随后的行星名称,所以我发现很难做到这一点。
最佳答案
也许你正在寻找的是mutually exclusive group .
parser = argparse.ArgumentParser(description="About the Solar System") # initialises argparse
parser.add_argument("--orderby", help="displays the planets ordered by mass, largest to smallest", action='store_true')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--list", help="displays the planets in alphabetical order", action='store_true')
group.add_argument("planet", help="displays information on the chosen <planet> and opens a wiki page", nargs="?", action="store")
args = parser.parse_args()
这会导致
% python3 args.py
usage: args.py [-h] [--orderby] (--list | planet)
args.py: error: one of the arguments --list planet is required
和
% python3 args.py --list
Namespace(list=True, orderby=False, planet=None)
% python3 args.py asdf
Namespace(list=False, orderby=False, planet='asdf')
% python3 args.py --list asdf
usage: args.py [-h] [--orderby] (--list | planet)
args.py: error: argument planet: not allowed with argument --list
关于python - 如何使用 2 个位置参数打印 argparse 上的帮助界面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36006882/