Search code examples
pythondocopt

Specify valid values for arguments using docopt


I am trying to use docopt for the first time. So far, this is the usage statement I have:

Test Control Program

Usage: 
  test.py bitwrite ([--off=<bits>...][--on=<bits>...])
  test.py regwrite ([regA | regB]<value>)

Options:
  -o <bits>... --off <bits>...  #Turn bits off
  -i <bits>... --on <bits>...   #Turns bits on

So, not I have no problem with test.py bitwrite -o bitA, bitB, bitC, bitD

Let's say that there is a user unfamiliar with my system and they need to know the proper values for the bits values.

Is there any way to specify this using the usage statement? I have tried several things and get nothing to work.


Solution

  • You can specify them in a separate part of the __doc__ , as an Example -

    Test Control Program
    
    Usage: 
      test.py bitwrite ([--off=<bits>...][--on=<bits>...])
      test.py regwrite ([regA | regB]<value>)
    
    Options:
      -o <bits>... --off <bits>...  #Turn bits off
      -i <bits>... --on <bits>...   #Turns bits on
    
    Arguments:
    
          bits: 1 - on
                0 - off
    

    Please note Arguments is not any special name recognized by docopt , its just any name, you can use any such appropriate name you want.

    In the above the Arguments section would show the valid values for bits, and other arguments .

    Then when running the above doc with --help option, you would get result as -

    >>>> python a.py --help
    Test Control Program
    
    Usage:
      test.py bitwrite ([--off=<bits>...][--on=<bits>...])
      test.py regwrite ([regA | regB]<value>)
    
    Options:
      -o <bits>... --off <bits>...  #Turn bits off
      -i <bits>... --on <bits>...   #Turns bits on
    
    Arguments:
    
          bits: 1 - on
                0 - off
    

    If you want to show the complete __doc__ without having to specify the --help or -h option, you can catch DocoptExit exception when calling the docopt() function and print the __doc__ at that time.

    Example -

    """Test Control Program
    
    Usage: 
      test.py bitwrite ([--off=<bits>...][--on=<bits>...])
      test.py regwrite ([regA | regB]<value>)
    
    Options:
      -o <bits>... --off <bits>...  #Turn bits off
      -i <bits>... --on <bits>...   #Turns bits on
    
    Arguments:
    
          bits: 1 - on
                0 - off
    
    """
    from docopt import docopt, DocoptExit
    
    
    if __name__ == '__main__':
        try:
            arguments = docopt(__doc__, version='Test Control Program')
            print(arguments)
        except DocoptExit:
            print(__doc__)