Docopt detailed introduction to using the command line parameter parsing tool in Python

Source: Internet
Author: User
Docopt is a tool used to parse command line parameters. if you want to append parameters to the Python program, you don't need to worry about it. The following article mainly introduces docopt, a command line parameter parsing tool in Python. the introduction is very detailed. let's take a look at it. Docopt is a tool used to parse command line parameters. if you want to append parameters to the Python program, you don't need to worry about it. The following article mainly introduces docopt, a command line parameter parsing tool in Python. the introduction is very detailed. let's take a look at it.

Preface

Docopt is an open source library. It has been described in detail in README, and many examples are provided for learning. This article also translates the content in README ......

The biggest feature of docopt is that you don't have to consider how to parse command line parameters. Instead, the parsing is completed when you write the desired format according to certain rules.

Docopt installation

Docopt has many versions that support different languages. the simplest docopt supports python scripts and docopt. java supports java scripts, while docopts supports shell scripts (the following example uses docopts as an example). For details, see docopt on github.

Install docopt

Take mac OS x as an example. install docopt before installing docopts. There are two installation methods:

Method 1

A relatively simple method is to directly use pip for installation,pip install docopt==0.6.2

Some mac may not support direct pip commands. you need to install pip first.

Method 2

You can also download the source code on github (docopt is an open-source project), and then usepython setup.py install Install

Install docopts

To install docopts, you must use method 2 of docopt installed above, download the source code on GitHub, and then install it using python,

Implementation and simple analysis of docopt

There is such an attribute in Python__doc__Its value is a string, which generally indicates the help information. docopt uses this attribute to replace the help information with the command line parameter parsing instructions, and then parse it.

Here is an example in docopt:


"""Naval Fate.Usage: naval_fate.py ship new 
 
  ... naval_fate.py ship 
  
    move 
    
    
      [--speed=
     
      ] naval_fate.py ship shoot 
       
       
         naval_fate.py mine (set|remove) 
         
         
           [--moored | --drifting] naval_fate.py (-h | --help) naval_fate.py --versionOptions: -h --help Show this screen. --version Show version. --speed=
          
            Speed in knots [default: 10]. --moored Moored (anchored) mine. --drifting Drifting mine."""from docopt import docoptif __name__ == '__main__': arguments = docopt(__doc__, version='Naval Fate 2.0') print(arguments)
          
         
        
       
      
     
    
   
  
 

In the above code segment, a large piece of help information is our command line parameter parsing description. at the function entrance, we call the docopt function for parsing. the returned arguments variable is a dictionary variable, it records whether the option is selected, the value of the parameter, and other information. when the program runs from the command line, we know the user input options and parameter information based on the records of the arguments variable.

Therefore, it is vital to write the command line parameter parsing instructions. the command line parsing information contains two parts: the mode format and the option description format.

Usage pattern format)

The usage mode starts with usage: and ends with a blank line. as shown in the code snippet above, it mainly describes the format used when you add command line parameters, that is, the format used, resolution is also performed in this format.

Each usage mode contains the following elements:

* Parameters

The parameters are enclosed by uppercase letters or angle brackets.

* Option

Start with a hyphen (-) or --. Only one letter is in the format of-o, and more than one letter is in the format of-output. You can also merge the options of multiple single letters.-ovi is equivalent to-o,-v, and-I. The options also have parameters. do not forget to add descriptions to the options.

The following describes the meanings of some identifiers used in the mode. correct use of these identifiers can better complete the parsing task:

* []

Optional elements. the elements in square brackets are optional.

*()

It indicates that the element must have one or more elements in the brackets.

* |

Mutually exclusive elements. only one element on either side of the vertical line can be left

*...

Indicates that the element can be repeated and the final parsing result is a list.

* [Options]

Specify specific options to complete specific tasks.

Option description format)

Option description is also required, especially when an option has a parameter and you need to assign a default value to it.

You can add parameters to an option in either of the following formats:


-O FILE -- output-FILE # Use the = symbol-I instead of commas.
 
  
, -- Input
  
   
# Use a comma, without the = symbol
  
 

To add a description for an option, you only need to use two spaces to separate the option and description.

When you add a default value to an option, add it to the selection description. the format is as follows [default: ]


--coefficient=K The K coefficient [default: 2.95]--output=FILE Output file [default: test.txt]--directory=DIR Some directory [default: ./]

If the option can be repeated, its value[default: ...]A list will be created. if it cannot be repeated, its value is a string.

Use

After understanding the format of the usage mode and option description, we can better understand the example.

The following figure shows the input information.

As mentioned above, the arguments parameter is a dictionary type that contains user input options and parameter information, or the preceding code snippet example. if the input we run from the command line is


python3 test.py ship Guardian move 100 150 --speed=15

The output parameters are as follows:


{'--drifting': False, '--help': False, '--moored': False, '--speed': '15', '--version': False, '
 
  ': ['Guardian'], '
  
   ': '100', '
   
    ': '150', 'mine': False, 'move': True, 'new': False, 'remove': False, 'set': False, 'ship': True, 'shoot': False}
   
  
 

From the print information, we can see that for options, the Boolean type indicates whether the user has entered this option. for parameters, the specific value is used for representation.

In this way, the program can get the next operation from the arguments variable. If you have not entered any parameters, the Usage prompt is displayed.

The above is a detailed description of docopt using the command line parameter parsing tool in Python. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.