The docopt command line parameter parsing tool in Python

  • 2020-05-27 06:09:46
  • OfStack


docopt is an open source library, the code address: https: / / github com/docopt/docopt. It has been introduced in detail in README, and many examples are attached for you to learn. This article is also a translation of README...

The great thing about docopt is that you don't have to worry about parsing the command-line arguments, but once you've written down the format you want according to rule 1, the parsing is done.

The installation of docopt

There are many versions of docopt, which support different languages. The simplest version of docopt supports python script, supports java script, and docopts supports shell script (the following example is mainly docopts). For details, please refer to docopt explanation of github

Install docopt

Take mac os x as an example for installation. Before installing docopts, docopt needs to be installed first. There are two installation methods

Method 1

The easier way is to install it directly with pip, pip install docopt==0.6.2

Some mac may not support the direct pip directive, so you need to install pip first

Method 2

You can also download the source code (docopt is an open source project) from github and then go through it python install The installation

Install docopts

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

Simple analysis of the implementation of docopt

So in Python you have this property __doc__ , its value is a string, 1 generally represents the help information, and docopt just makes use of this 1 attribute, replaces the help information with the command line parameter parsing explanation, and then parses it.

Here's an example from docopt:

"""Naval Fate.
Usage: ship new <name>... ship <name> move <x> <y> [--speed=<kn>] ship shoot <x> <y> mine (set|remove) <x> <y> [--moored | --drifting] (-h | --help) --version
 -h --help  Show this screen.
 --version  Show version.
 --speed=<kn> Speed in knots [default: 10].
 --moored  Moored (anchored) mine.
 --drifting Drifting mine.
from docopt import docopt
if __name__ == '__main__':
 arguments = docopt(__doc__, version='Naval Fate 2.0')

The above code snippet, a large section of the help information is our 1 command-line argument parsing, at the entrance of the function call docopt function parses, return the typical variable arguments variable is one word, it records the option is chosen, what is the value of the parameter information, such as when the program is run from the command line, we are according to the records to know arguments variable user input information of options and parameters.

So it's important to write a good description of command-line argument parsing, which consists of two parts, using the schema format and the option description format.

Use mode format (Usage pattern format)

The usage pattern starts with usage: and ends with a blank line, as shown in the code snippet above, which mainly describes the format in which the user adds command-line arguments, that is, the format in which they are used, and is parsed.

Each usage pattern contains the following elements:

* parameters

Use uppercase or Angle brackets for arguments < > Surrounded.

* option

The options start with a short horizontal line -- or --. Format -o for 1 letter, output for more than 1 letter. You can also combine multiple single-letter options. -ovi is the same as -o, -v, -i. Options can also have arguments, so don't forget to add descriptions to the options.

Here are some of the meanings of the tags used in the usage pattern. Using them correctly can do the parsing task better:

* []

Represents an optional element, and the elements in square brackets are optional

* ()

That means that you have to have elements, you have to have elements in parentheses, even if you have multiple elements and you have to choose one of them.

* |

Mutually exclusive elements, elements on either side of the vertical line can only have 1 left

* ...

The representation element can be repeated, and the end result is a list

* [options]

Specify specific options to complete specific tasks.

Option description format (Option description format)

An option description is also essential, especially if the selected item takes a parameter and needs to be assigned a default value.

There are two formats for adding parameters to an option:

-o FILE --output-FILE  #  Instead of using commas, use  =  symbol 
-i <file>, --input <file> #  Use commas, not commas  =  symbol 

To add a description to the option, simply separate the option and the description with two Spaces.

When you add a default value to an option, add it after the selection description in the following format [default: < my-default-value > ]

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

If the option is repeatable, then its value [default: ...] There will be a list of list, and if it cannot be repeated, it will have a value of 1 string.


Once you understand the use of the schema format and the options description format, you will be better able to follow the examples given.

The next step is to get the input information.

As mentioned earlier, the arguments parameter is a dictionary type, which contains the options and parameter information entered by the user, or the code snippet example above, if the input we run from the command line is

python3 ship Guardian move 100 150 --speed=15

Then the print arguments parameter is as follows:

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

As you can see from the print information, a Boolean is used for the option to indicate whether the user entered the option, and a value is used for the parameter.

In this way, the program can get the operation of the next step from the arguments variable. If the user does not enter any parameters, the Usage instructions prompt for input.


The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.

Related articles: