所以我认为argparse非常好但是我怎么能在argparse / python中做这样的事情?
例如:
myprog del <username> (remove only config entry)
myprog del -A <username> (remove all of the user...)
myprog add <username> (must be 1 sub-arg, not more)
myprog change <old-username> <to-new-username> (must be 2 sub-args, not more)
myprog list (no sub argument)
myprog list -A (list ALL)
答案 0 :(得分:0)
这看起来像使用子分析器的直接案例
https://docs.python.org/3/library/argparse.html#sub-commands
调整文档中的示例
parser = argparse.ArgumentParser(prog='PROG')
...
subparsers = parser.add_subparsers(dest='cmd', help='sub-command help')
# create the parser for the "a" command
parser_a = subparsers.add_parser('del', help='a help')
parser_a.add_argument('username', ...)
parser_a.add_argument('-A', type='store_true')
# create the parser for the "b" command
parser_b = subparsers.add_parser('add', help='b help')
parser_b.add_argument('username')
# change gets 2 positionals
# list gets one -A
....
args = parser.parse_args()
if args.cmd == 'del':
# delete args.username
....
args.cmd
告诉你给出了哪个命令。文档(以及其他SO问题)显示了如何将函数与每个命令相关联。