Home > Backend Development > Python Tutorial > Detailed introduction to using docopt, the command line parameter parsing tool in Python

Detailed introduction to using docopt, the command line parameter parsing tool in Python

高洛峰
Release: 2017-03-28 09:22:42
Original
1885 people have browsed it

docopt is a tool used to parse command line parameters. When you want to append parameters to a Python program, you no longer need to worry about it. The following article mainly introduces the relevant information of docopt, the command line parameter parsing tool in Python. The introduction is very detailed. Friends who need it can take a look below.

Preface

docopt is an open source library. It has been introduced in detail in the README, and it also comes with many examples for learning. This article also translates the content in the README...

docopt’s biggest feature is that you don’t have to worry about how to parse the command line. Parameters, but when you write out the format you want according to certain rules, the analysis is completed.

docopt installation

docopt has many versions, each supporting different languages. The simplest docopt supports python scripts, docopt. Java supports java scripts, and docopts supports shell scripts (the following examples mainly use docopts as an example). For details, please refer to github's docopt instructions

Installing docopt

Take mac os x as an example to install. Before installing docopts, you need to install docopt first. There are two installation methods

Method one

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

Some macs may not support direct pip instructions, 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 use python setup.py install Install

Install docopts

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

docopt implementation simple analysis

There is such an attribute in Python__doc__ , its value is a string, generally indicating help information, and docopt takes advantage of this attribute to replace the help information with command line parameter parsing instructions, and then parse it.

Let’s take an example from docopt to illustrate:


"""Naval Fate.
Usage:
 naval_fate.py ship new <name>...
 naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
 naval_fate.py ship shoot <x> <y>
 naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
 naval_fate.py (-h | --help)
 naval_fate.py --version
Options:
 -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__ == &#39;__main__&#39;:
 arguments = docopt(__doc__, version=&#39;Naval Fate 2.0&#39;)
 print(arguments)
Copy after login

In the above code segment, a large section of the help information is ours Instructions for parsing command line parameters. Call the docopt function at the function entry for parsing. The returned arguments variable is a lexicon variable. It records whether the option is selected, what the value of the parameter is, and other information. When the program is run from the command line , we know the options and parameter information entered by the user based on the records of the arguments variable.

So how to write command line parameter parsing instructions becomes crucial. The command line parsing information contains two parts, namely the usage pattern format and the option description format.

Usage pattern format (Usage pattern format)

The usage pattern starts with usage: and ends with a blank line, as shown in the above code snippet, It mainly describes the format when users add command line parameters, that is, the format when used, and the parsing is also performed according to this format.

Each usage pattern contains the following elements:

* Parameters

Parameters should be in uppercase letters or enclosed in angle brackets <>.

* Options

Options start with a dash - or -. The format is -o when there is only one letter, and --output when there is more than one letter. At the same time, you can also combine multiple single-letter options. -ovi is equivalent to -o, -v, -i. Options can also have parameters. Don’t forget to add a description to the options at this time.

The following is the meaning of some identifiers used in the usage pattern. Using them correctly can better complete the parsing task:

* []

represents optional elements, the elements in square brackets are optional

* ()

represents the required elements, the elements in brackets You must have one, even if you choose one among several.

* |

Mutually exclusive elements, only one element on both sides of the vertical bar can be left

* ...

means that the element can appear repeatedly, and the final parsed result is a list

* [options]

Specify specific options to complete specific task.

Option description format

Option description is also essential, especially when the option has parameters and needs to be When it is assigned a default value.

There are two formats for adding parameters to options:


-o FILE --output-FILE  # 不使用逗号,使用 = 符号
-i <file>, --input <file> # 使用逗号,不使用 = 符号
Copy after login

To add descriptions for options, just separate the options and descriptions with two spaces. .

When adding a default value to an option, just add it after 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: ./]
Copy after login

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

Use

After understanding the usage pattern format and option description format, you can better understand it with the examples given.

The next step is to get the input information.

在前面提到arguments参数是一个字典类型,包含了用户输入的选项和参数信息,还是上面的代码段例子,假如我们从命令行运行的输入是


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

那么打印arguments参数如下:


{&#39;--drifting&#39;: False,
 &#39;--help&#39;: False,
 &#39;--moored&#39;: False,
 &#39;--speed&#39;: &#39;15&#39;,
 &#39;--version&#39;: False,
 &#39;<name>&#39;: [&#39;Guardian&#39;],
 &#39;<x>&#39;: &#39;100&#39;,
 &#39;<y>&#39;: &#39;150&#39;,
 &#39;mine&#39;: False,
 &#39;move&#39;: True,
 &#39;new&#39;: False,
 &#39;remove&#39;: False,
 &#39;set&#39;: False,
 &#39;ship&#39;: True,
 &#39;shoot&#39;: False}
Copy after login

从打印信息可以看到,对于选项,使用布尔型来表示用户是否输入了该选项,对于参数,则使用具体值来表述。

这样一来,程序就可以从arguments变量中得到下一步的操作了。若是用户什么参数都没输入,则打印Usage说明提示输入内容。

The above is the detailed content of Detailed introduction to using docopt, the command line parameter parsing tool in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template