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

时间:2016-09-02 07:39:07

标签: python docopt

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

python test.py --list=all

我尝试将其运行为:{{1}}但它不接受该值,只显示docopt字符串。

我希望list参数的值为'all'或'available'。有什么办法可以实现吗?

1 个答案:

答案 0 :(得分:1)

这是一个实现你想要的例子:

<强> 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 
相关问题