Python argparse 模块使用

Python argparse module usage

我有一个这样调用的程序:

program.py add|remove|show 

这里的问题是,根据 add/remove/show 命令,它需要可变数量的参数,就像这样:

program.py add "a string" "another string"
program.py remove "a string"
program.py show

因此,'add' 命令会接受 2 个字符串参数,而 'remove' 命令只会接受 1 个参数,而 'show' 命令不会接受任何参数。 我知道如何使用模块 argparse 制作一个基本的参数解析器,但我没有太多经验,所以我从这里开始:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("command", choices=["add", "remove", "show"])

但我不知道如何继续以及如何根据命令实现此功能。提前致谢。

您正在寻找 argparse 的子解析器...

parser = argparse.ArgumentParser(prog='PROG')
subparsers = parser.add_subparsers(help='sub-command help')

# create the parser for the "add" command
parser_add = subparsers.add_parser('add', help='add help')
# [example] add an argument to a specific subparser
parser_add.add_argument('bar', type=int, help='bar help')

# create the parser for the "remove" command
parser_remove = subparsers.add_parser('remove', help='remove help')

# create the parser for the "show" command
parser_show = subparsers.add_parser('show', help='show help')

此示例代码是从语言 reference documentation.

中窃取的,只做了很少的修改