【问题标题】:Specify an option one or more times in docopt在 docopt 中指定一个选项一次或多次
【发布时间】:2019-01-11 23:01:12
【问题描述】:

我有一个程序(在 python 中,但这不重要),它接受一些选项一次或多次,例如:

# Valid cases:
python test.py --o 1 --p a <file>
python test.py --o 1 --o 2 --p a --p b <file>
# Invalid:
python test.py --o a <file>
python test.py --p a <file>
python test.py <file>

此脚本有效:

#!/usr/bin/env python2.7

"""Test

Usage:
  test.py --o=<arg> [--o=<arg>...] --p=<arg> [--p=<arg>...] <file>

"""
from docopt import docopt


if __name__ == '__main__':
    arguments = docopt(__doc__, version='Test 1.0')
    print(arguments)

但是该选项被重复并且感觉非常难看。我尝试了以下方法:

test.py --o=<arg>[...] --p=<arg>[...] <file>
test.py (--o=<arg>)[...] (--p=<arg>)[...] <file>
test.py (--o=<arg>[...]) (--p=<arg>[...]) <file>

但它们都不起作用。另一种方法是使选项完全可选并在程序中检查其值:

  test.py [--o=<arg>...] [--p=<arg>...] <file>
  ...
  if len(arguments["--o"]) < 1:
    raise ValueError("One or more --o required")
  if len(arguments["--p"]) < 1:
    raise ValueError("One or more --p required")

但我觉得应该有一个简单的解决方案可以直接使用 docopt 来做到这一点。有什么漂亮的方法吗?

【问题讨论】:

    标签: docopt


    【解决方案1】:

    有点晚了,但是

    Usage:
      test.py (--o=<arg>)... (--p=<arg>)... <file>
    

    做你想做的。

    Usage:
      test.py (--o=<arg>...) (--p=<arg>...) <file>
    

    也可以工作。

    【讨论】:

    • @Calimo 很高兴知道:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多