如何在docopt python中为参数设置特定的值



我正在尝试使用docopt的python代码。我实际上只需要为参数设置特定的值。我的用法如下:

"""
Usage:
test.py --list=(all|available)
Options:
    list    Choice to list devices (all / available)
"""

我已经尝试将其运行为:python test.py --list=all,但它不接受该值,只是显示docopt字符串。

我希望列表参数的值是'all'或'available'。有什么办法可以做到这一点吗?

这里有一个示例来实现您想要的:

test.py:

"""
Usage:
  test.py list (all|available)
Options:
  -h --help     Show this screen.
  --version     Show version.
  list          Choice to list devices (all / available)
"""
from docopt import docopt
def list_devices(all_devices=True):
    if all_devices:
        print("Listing all devices...")
    else:
        print("Listing available devices...")

if __name__ == '__main__':
    arguments = docopt(__doc__, version='test 1.0')
    if arguments["list"]:
        list_devices(arguments["all"])

使用这个脚本,您可以运行如下语句:

python test.py list all

或:

python test.py list available