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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

See all articles