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

Mar 28, 2017 am 09:22 AM
docopt python

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

Python hourglass graph drawing: How to avoid variable undefined errors? Python hourglass graph drawing: How to avoid variable undefined errors? Apr 01, 2025 pm 06:27 PM

Getting started with Python: Hourglass Graphic Drawing and Input Verification This article will solve the variable definition problem encountered by a Python novice in the hourglass Graphic Drawing Program. Code...

Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Apr 01, 2025 pm 05:24 PM

Choice of Python Cross-platform desktop application development library Many Python developers want to develop desktop applications that can run on both Windows and Linux systems...

Do Google and AWS provide public PyPI image sources? Do Google and AWS provide public PyPI image sources? Apr 01, 2025 pm 05:15 PM

Many developers rely on PyPI (PythonPackageIndex)...

How to efficiently count and sort large product data sets in Python? How to efficiently count and sort large product data sets in Python? Apr 01, 2025 pm 08:03 PM

Data Conversion and Statistics: Efficient Processing of Large Data Sets This article will introduce in detail how to convert a data list containing product information to another containing...

How to optimize processing of high-resolution images in Python to find precise white circular areas? How to optimize processing of high-resolution images in Python to find precise white circular areas? Apr 01, 2025 pm 06:12 PM

How to handle high resolution images in Python to find white areas? Processing a high-resolution picture of 9000x7000 pixels, how to accurately find two of the picture...

How to solve the problem of file name encoding when connecting to FTP server in Python? How to solve the problem of file name encoding when connecting to FTP server in Python? Apr 01, 2025 pm 06:21 PM

When using Python to connect to an FTP server, you may encounter encoding problems when obtaining files in the specified directory and downloading them, especially text on the FTP server...

See all articles