Python command-line tour - Preliminary argparse

"Explain open source project series' start - let people interested in open source projects are no longer afraid, let sponsors open source projects are no longer alone. Follow our articles, you'll discover the fun of programming, the use of open source projects and found to be involved so simple. Feel free to contact us to our contributors, so that more people fall in love with open source, open source contribution ~

Foreword

Have you wondered after typing some commands at the command line, how it was analyzed and executed? If considered by themselves achieve a command-line tool to help you perform and processing tasks? Whether to find out about your side of the Python has a rich library to help you easily create a command-line tool?

Do not worry, this article as a Python command-line tour of the first chapter will take you step by step to uncover the veil of command line parsing, describes how to use the built-in Python argparsestandard library to parse the command line, and introduces distinctive in a subsequent series of articles third-party command-line libraries, talk about their similarities and differences, and then explore the full experience of this journey.

本系列文章默认使用 Python 3 作为解释器进行讲解。
若你仍在使用 Python 2,请注意两者之间语法和库的使用差异哦~

Introduction

argparseAs a built-in Python standard library provides a simpler way to write a command line interface. When you define which parameters are required in the program, argparsewill be from sys.argvobtaining the command line is parsed to correct or respond to illegal input, it can also automatically generate help information and instructions for use.

Quick Start

Set parser

The first step is to set the parser, subsequent parsing command line parser to rely on this, it can be converted to a Python command-line string object.
By instantiating argparse.ArgumentParser, given a number of optional parameters, we can set a parser:

import argparse
parser = argparse.ArgumentParser(
    description='My Cmd Line Program',
)

Defined parameters

By ArgumentParser.add_argumentsetting the parameter information parser way to tell what the parser command line string should resolve what type Python objects, such as:

# 添加 nums 参数,在使用信息中显示为 num
# 其类型为 int,且支持输入多个,且至少需要提供一个
parser.add_argument('nums',  metavar='num', type=int, nargs='+',
                    help='a num for the accumulator')
# 添加 --sum 参数,该参数被 parser 解析后所对应的属性名为 accumulate
# 若不提供 --sum,默认值为 max 函数,否则为 sum 函数
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the nums (default: find the max)')

Parse command line

After the well defined parameters, it can be used ArgumenteParser.parse_argsa method to resolve a set of command line arguments.

默认情况下,参数取自 sys.argv[1:],它就是你在命令行敲入的一段命令(不含文件名)所对应的一个字符串列表。
比如,若你输入 python3 cmd.py --sum 1 2 3,那么 sys.argsv[1:] 就是 ['--sum', '1', '2', '3']

当然,也可以通过 parse_args 入参来指定一组命令行参数字符串:

args = parser.parse_args(['--sum', '-1', '0', '1'])
print(args) # 结果:Namespace(accumulate=<built-in function sum>, nums=[-1, 0, 1])

业务逻辑

解析好命令行后,我们就可以从解析结果中获取每个参数的值,进而根据自己的业务需求做进一步的处理。
比如,对于上文中所定义的 nums 参数,我们可以通过解析后的结果中的 accumulate 方法对其进行求最大值或求和(取决于是否提供 --sum 参数)。

result = args.accumulate(args.nums)
print(result)  # 基于上文的 ['--sum', '-1', '0', '1'] 参数,accumulate 为 sum 函数,其结果为 0

代码梳理

通过上文的讲解,完成一个命令行工具的步骤是不是挺简单易懂呢?我们将上文的代码汇总下,以有一个更清晰的认识:

# cmd.py
import argparse

# 1. 设置解析器
parser = argparse.ArgumentParser(
    description='My Cmd Line Program',
)

# 2. 定义参数
parser.add_argument('nums',  metavar='num', type=int, nargs='+',
                    help='a num for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the nums (default: find the max)')

# 3. 解析命令行
args = parser.parse_args()

# 4. 业务逻辑
result = args.accumulate(args.nums)
print(result)

若我们需要对一组数字求和,只需执行:

$ python3 cmd.py --sum -1 0 1
0

若我们需要对一组数字求最大值,只需执行:

$ python3 cmd.py -1 0 1
1

如果给定的参数不是数字,则会报错提示:

$ python3 cmd.py a b c
usage: cmd.py [-h] [--sum] num [num ...]
cmd.py: error: argument num: invalid int value: 'a'

我们还可以通过 -h--help 参数查看其自动生成的使用说明和帮助:

usage: cmd.py [-h] [--sum] num [num ...]

My Cmd Line Program

positional arguments:
  num         a num for the accumulator

optional arguments:
  -h, --help  show this help message and exit
  --sum       sum the nums (default: find the max)

小结

怎么样?揭开命令行工具的神秘面纱后,是不是发现它并没有想象中的困难?反倒是感受到一种简单而又强大的优雅呢?

不过这还远远不是 argparse 的全部面貌。对于一些复杂的情况,比如各种类型参数、参数前缀、参数组、互斥选项、嵌套解析、自定义帮助等等,我们都还没涉及探讨。

在下一篇文章中,让我们来一起深入了解 argparse,感受它的魅力吧!

关注公众号加入交流群,一起讨论有趣的技术话题

Guess you like

Origin www.cnblogs.com/xueweihan/p/11341402.html