更改强制参数的数量取决于选项(argparse)

Change number of mandatory arguments depends on option (argparse)

我想用 argparse 制作简单的命令行:

usage: downtime [-h] [-d] [-l | -f] [-s] host duration

positional arguments:
  host            Host to schedule. Local fqdn used if not specified.
  duration        Duration of downtime (minutes), 15 if not specified

optional arguments:
  -h, --help      show this help message and exit
  -d, --debug     Print debug info
  -l, --flexible  Use f_L_exible downtime (used by default)
  -f, --fixed     Use _F_ixed downtime

我想添加“-s”-'show'选项:

foobar -s host
   -s           Show info for host

如果有“-s”开关,我找不到说 argparse '改变位置参数含义的方法。或者至少使 'number' 可选。

我该怎么做,或者这对 argparse 来说是不可能的?谢谢

代码:

p = argparse.ArgumentParser()
p.add_argument('host', help = "Host to schedule. Local fqdn used if not specified.", nargs = '?'  default=alias)
p.add_argument('duration', type = int, help = 'Duration of downtime (minutes), 15 if not specified', default=15)
p.add_argument('-d', '--debug', action='store_true', help = 'Print debug info')
g = p.add_mutually_exclusive_group()
g.add_argument('-l', '--flexible', help = "Use f_L_exible downtime (used by default)", action='store_true')
g.add_argument('-f', '--fixed', help = 'Use _F_ixed downtime', action="store_false")
mode2 = p.add_argument_group('show')
mode2.add_argument('-s', '--show', help = 'show downtimes for host', action="store_true")
args = p.parse_args()

nargs='?' 添加到持续时间:

p.add_argument('duration', type = int, nargs='?', help = 'Duration of downtime (minutes), 15 if not specified', default=15)

将用法更改为:

usage: downtime [-h] [-d] [-l | -f] [-s] host [duration]

通过此更改,duration 始终是可选的。在它被要求之前,'default=15'什么也没做。现在默认值意味着什么。

似乎总是需要 host。这是一件好事,因为不止一个 'optional' 位置会使事情复杂化(这是可能的,但更棘手)。

-s 与类似的东西一起使用:

if args.s:
    print_show(args.host)
    # ignore args.duration regardless of whether it is default or not
    # or object if args.duration  is not its default value
else:
    <do something else with args.host and args.duration>