search
HomeBackend DevelopmentPython TutorialDetailed introduction to using docopt, the command line parameter parsing tool in 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)

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> # 使用逗号,不使用 = 符号

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: ./]

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

那么打印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}

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

这样一来,程序就可以从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
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
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),