【问题标题】:Using docopt double dash option with optional parameter?使用带有可选参数的 docopt 双破折号选项?
【发布时间】:2019-10-16 04:21:01
【问题描述】:

使用 docopt,有没有办法制作一个双虚线参数,可以使用和不使用等号?

我希望以下两个命令都使 --tls 为真:

cmd --tls
cmd --tls=true

我似乎只能通过使用使其中一个或另一个工作

Options:
  --tls

Options:
  --tls=false                  

用逗号分隔它们似乎不起作用

Options:
  --tls, --tls=false                  

【问题讨论】:

  • 参见stackoverflow.com/q/30896982/3001761 了解如何在argparse 中执行类似操作;你也许可以在它的帮助下逆向工作!
  • 这可行:--tls=(true|false) Use TLS-encryption [default: true],但可能不是您真正想要的。考虑打开issue

标签: python docopt


【解决方案1】:

我也有同样的问题。 我找不到解决方案,但这是我所拥有的最佳解决方法:

"""
Usage:
  test.py [tls [--true|--false]]
"""
from docopt import docopt
arguments = docopt(__doc__)
if arguments['tls'] and not (arguments['--true'] or arguments['--false']):
    arguments['--true'] = True

所以参数选项是:

cmd
cmd tls
cmd tls --true
cmd tls --false

注意这是区分大小写的,如果你把TLS大写可能会有错误:https://github.com/docopt/docopt/issues/460

 

另一种选择:

"""
Usage:
    script.py [--tls [<tlsval>]]
"""
from docopt import docopt
arguments = docopt(__doc__)
assert arguments['<tlsval>'] in (None, 'true', 'false'), "invalid tls value -- expected true or false"

 

 

抱歉所有的修改,但这里还有一个:

"""
Usage:
   script.py [--MAS|--GPI [RESEND|ADD|REMOVE|SKU]]

Options:
    --MAS                   only do MAS step
    --GPI                   only do GPI step, optionally specify ADD/REMOVE/SKU (default is RESEND)
        RESEND            only GPI, strategy=RESEND (default for --GPI)
        ADD               only GPI, strategy=ADD
        REMOVE            only GPI, strategy=REMOVE
        SKU               only GPI, strategy=SKU
"""
from docopt import docopt
arguments = docopt(__doc__)
strategy = [k for k in ['RESEND', 'ADD', 'REMOVE', 'SKU'] if arguments[k]]
strategy = strategy[0] if strategy else "RESEND" #resend is default

这个给你--argument但不能在--argument之后有=

【讨论】:

    猜你喜欢
    • 2021-10-20
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 2021-05-06
    相关资源
    最近更新 更多