The docopt of the command-line parameter parsing tool in Python is described in detail

Source: Internet
Author: User
Docopt is a tool for parsing command-line arguments, and you don't need to worry about it when you want to attach parameters to a Python program. The following article mainly introduces the docopt of command-line parameter parsing tool in Python, introduces the very detailed, the needs of friends below to see it together.

Objective

Docopt is an open source library. It has been described in detail in the Readme, and also comes with a lot of examples to learn, this article is also translated in the Readme content ...

The biggest feature of Docopt is that you don't have to think about how to parse command-line arguments, but when you write the formatting you want in your mind, the parsing is done.

Installation of docopt

There are many versions of docopt, each supporting a different language, and the simplest docopt supports Python scripts, Docopt.java supports Java scripts, and docopts supports shell scripts (The following example mainly takes docopts as an example), see the docopt description of GitHub

Installing docopt

Installation of Mac OS X as an example, before installing docopts, you need to install docopt first, there are two methods of installation

Method One

The simpler way is to install directly with PIP,pip install docopt==0.6.2

Some Macs may not support direct PIP instructions and need to install PIP first

Method Two

You can also download the source code on GitHub (Docopt is an open source project) and then python setup.py install install

Installing docopts

Install docopts must use the above installation Docopt method Two, on GitHub download the source code, and then use the Python installation, downloading the address

Simple analysis of the implementation of DOCOPT

There is a property in Python __doc__ , its value is a string, generally represents the help information, and docopt is the use of this property, the Help information is replaced by the command line parameter parsing instructions, and then parse it.

Give an example in Docopt to illustrate:


"" "Naval Fate.Usage:naval_fate.py ship new <name> ... naval_fate.py ship <name> move <x> <y> [--sp Eed=<kn>] naval_fate.py ship shoot <x> <y> naval_fate.py Mine (set|remove) <x> <y> [--moore D | --drifting] naval_fate.py (-H |--help) naval_fate.py--versionoptions:-H--help Show this screen  .--version  Sho W version. --speed=<kn> 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 snippet, a large section of the Help information is our command-line parameter resolution description, the function at the entrance of the call docopt function to parse, the return of the arguments variable is a word typical variable, it records the option is selected, the value of the parameter is what information, when the program runs from the command line, We are based on the record of the arguments variable to know the user input options and parameter information.

So how to write good command-line parameter parsing instructions becomes critical, and the command-line parsing information consists of two parts, namely the use of pattern format and option description format.

Use pattern formatting (usage pattern format)

Usage pattern with usage: Start with a blank line, as shown in the previous code snippet, which mainly describes the format of the user when adding command-line arguments, that is, the format used, and parsing is done in this format.

Each usage pattern contains the following elements:

* Parameters

Parameters use uppercase letters or use angle brackets <> surround them.

* Options

The option starts with a dash-or--。 Only one letter when the format is-O, more than one letter when--output. You can also combine multiple single-letter options,-ovi equivalent to-O,-V,-I. Option can also have parameters, don't forget to add a description to the option at this time.

The next step is to use the meanings of some of the identities used in the pattern and use them correctly to perform the parsing tasks better:

* []

Represents an optional element, the element inside the square brackets is dispensable

* ()

Represents the element that must be, the element inside the parentheses must have, even if it is selected in more than one.

* |

Mutually exclusive elements, the elements on both sides of the vertical line can only have one left

* ...

The representative element can be repeated, and the result of the final parsing is a list

* [Options]

Specify specific options to complete a specific task.

Option description Format (option description format)

The option description is also necessary, especially if the selected item has parameters, and it also needs to be assigned a default value.

There are two formats for adding parameters to an option:


-O FILE--output-file  # do not use commas, use = sign-I <file>,--input <file> # Use commas, do not use = Symbol

To add a description for the option, you only need to separate the options and descriptions with two spaces.

To add a default value for an option, add it to the selection description later, 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 Direct Ory [Default:./]

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

Use

After understanding the use of pattern format and option description format, the example given in the match can be better understood.

The next step is to get the input information.

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


Python3 test.py ship Guardian Move--speed=15

Then print the arguments parameter as follows:


{'--drifting ': false, '--help ': false, '--moored ': false, '--speed ': ' ", '--version ': false, ' <name> ': [' Guardian '], ' <x> ': ' + ', ' <y> ': ' Mine ', ' ' Move ': ' false ', ' ' moves ': True, ' new ': false, ' remove ': false, ' Set ': false, ' Shi P ': True, ' shoot ': False}

As you can see from the printing information, for options, Boolean is used to indicate whether the user has entered the option, and for parameters, the specific value is used to express it.

In this way, the program can get the next step from the arguments variable. If the user does not enter any parameters, the Print usage note prompts for input.

Related Article

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.