Search code examples
pythondocopt

How to set only specific values for a parameter in docopt python?


I am trying to use docopt for a python code. I actually need to set only specific values for a parameter. My usage is as below:

"""
Usage:
test.py --list=(all|available)

Options:
    list    Choice to list devices (all / available)
"""

I've tried to run it as: python test.py --list=all but it doesn't accept the value and just displays the docopt string .

I want the value of list parameter to be either 'all' or 'available'. Is there any way this can be achieved?


Solution

  • Here's an example to achieve what you want:

    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"])
    

    With this script you could run statements like:

    python test.py list all
    

    or:

    python test.py list available