我想写我的python脚本解析其中的命令参数应该按以下顺序解析嵌套的可选参数,argsparse在蟒蛇
OUTPUT: cli unmount [-h] -f FS_NAME [-n NODE_SPEC] [--evict [--force]]]
我能编写除最后一个之外的其余命令的代码。 [--evict [--force]]
。这意味着--force
参数仅适用于给出--evict
的情况。
parser = argparse.ArgumentParser('CLI demo')
sub_parser = parser.add_subparsers()
unmount = sub_parser.add_parser('unmount')
unmount.add_argument("-f", "--fs", dest="fs_name", required=True, help="filesystem name.")
unmount.add_argument("-n", "--nodes", dest="nodes", metavar='NODE_SPEC', help="pdsh style nodes hostnames (If this parameters ")
这些都是我已添加的可选子的说法,--force
到可选父的说法,--evict
两种方法,
方法1:
evict_parser = unmount.add_subparsers()
evict = evict_parser.add_parser("--evict", help="evict lustre clients before unmount.")
evict.add_argument("--force", dest="force", action="store_true", default=False, help="force mode for evict lustre clients.")
parser.parse_args()
和方法2:
parent_cmd_parser = argparse.ArgumentParser(add_help=F)
parent_cmd_parser.add_argument("--force", dest="force", action="store_true", default=False, help="force mode for evict lustre clients.")
evict_parser = unmount.add_subparsers()
evict = evict_parser.add_parser("--evict", help="evict lustre clients before unmount.", parents=[parent_cmd_parser])
不幸的是没有工作。在第一种情况下,我没有得到所需的帮助输出/使用帮助,在第二种情况下--force
参数被隐藏。
如果'--force'没有使用'--evict',会发生什么?如果首先给出呢? – hpaulj
@hpaulj,在这种情况下,这将是错误的。因为只有在启用了--evict时才会启用--force。 –