我有一个程序(在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 . 有一种美妙的方式吗?