argparse - Parser for command-line options, arguments and sub-commands - 1

argparse - Parser for command-line options, arguments and sub-commands - 1

argparse - Parser for command-line options, arguments and sub-commands
https://docs.python.org/3/library/argparse.html

argparse - 命令行选项、参数和子命令解析器
https://docs.python.org/zh-cn/3/library/argparse.html

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.
argparse 模块可以让人轻松编写用户友好的命令行接口。程序定义它需要的参数,然后 argparse 将弄清如何从 sys.argv 解析出那些参数。argparse 模块还会自动生成帮助和使用手册,并在用户给程序传入无效参数时报出错误信息。

parser ['pɑːsə]:n. 分析程序,语法剖析程式
argument ['ɑːgjʊm(ə)nt]:n. 论证,论据,争吵,内容提要

1. Example

The following code is a Python program that takes a list of integers and produces either the sum or the max:
以下代码是一个 Python 程序,它获取一个整数列表并计算总和或者最大值:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')

parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max,
                    help='sum the integers (default: find the max)')

if __name__ == '__main__':
    args = parser.parse_args()
    print(args.accumulate(args.integers))

Assuming the Python code above is saved into a file called yongqiang.py, it can be run at the command line and provides useful help messages:
假设上面的 Python 代码保存在名为 yongqiang.py 的文件中,它可以在命令行运行并提供有用的帮助消息:

strong@foreverstrong:~/tensorflow_work/R2CNN_Faster-RCNN_Tensorflow$ python3 yongqiang.py -h
usage: yongqiang.py [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
  N           an integer for the accumulator

optional arguments:
  -h, --help  show this help message and exit
  --sum       sum the integers (default: find the max)
strong@foreverstrong:~/tensorflow_work/R2CNN_Faster-RCNN_Tensorflow$

When run with the appropriate arguments, it prints either the sum or the max of the command-line integers:
当使用适当的参数运行时,它会输出命令行传入整数的总和或者最大值:

strong@foreverstrong:~/tensorflow_work/R2CNN_Faster-RCNN_Tensorflow$ python3 yongqiang.py 1 2 3 4
4
strong@foreverstrong:~/tensorflow_work/R2CNN_Faster-RCNN_Tensorflow$ 
strong@foreverstrong:~/tensorflow_work/R2CNN_Faster-RCNN_Tensorflow$ python3 yongqiang.py 1 2 3 4 --sum
10
strong@foreverstrong:~/tensorflow_work/R2CNN_Faster-RCNN_Tensorflow$

If invalid arguments are passed in, it will issue an error:
如果传入无效参数,则会报出错误:

strong@foreverstrong:~/tensorflow_work/R2CNN_Faster-RCNN_Tensorflow$ python3 yongqiang.py a b c
usage: yongqiang.py [-h] [--sum] N [N ...]
yongqiang.py: error: argument N: invalid int value: 'a'
strong@foreverstrong:~/tensorflow_work/R2CNN_Faster-RCNN_Tensorflow$

The following sections walk you through this example.
以下部分将引导你完成这个示例。

positional [pə'zɪʃənəl]:adj. 位置的,地位的
optional ['ɒpʃ(ə)n(ə)l]:adj. 可选择的,随意的

1.1 Creating a parser - 创建一个解析器

The first step in using the argparse is creating an ArgumentParser object:
使用 argparse 的第一步是创建一个 ArgumentParser 对象:

parser = argparse.ArgumentParser(description='Process some integers.')

The ArgumentParser object will hold all the information necessary to parse the command line into Python data types.
ArgumentParser 对象包含将命令行解析成 Python 数据类型所需的全部信息。

1.2 Adding arguments - 添加参数

Filling an ArgumentParser with information about program arguments is done by making calls to the add_argument() method. Generally, these calls tell the ArgumentParser how to take the strings on the command line and turn them into objects. This information is stored and used when parse_args() is called. For example:
给一个 ArgumentParser 添加程序参数信息是通过调用 add_argument() 方法完成的。通常,这些调用指定 ArgumentParser 如何获取命令行字符串并将其转换为对象。这些信息在 parse_args() 调用时被存储和使用。例如:

parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')

Later, calling parse_args() will return an object with two attributes, integers and accumulate. The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.
稍后,调用 parse_args() 将返回一个具有 integers 和 accumulate 两个属性的对象。integers 属性将是一个包含一个或多个整数的列表,而 accumulate 属性当命令行中指定了 --sum 参数时将是 sum() 函数,否则则是 max() 函数。

fill [fɪl]:vt. 装满,使充满,满足,堵塞,任职 vi. 被充满,膨胀 n. 满足,填满的量,装填物

1.3 Parsing arguments - 解析参数

ArgumentParser parses arguments through the parse_args() method. This will inspect the command line, convert each argument to the appropriate type and then invoke the appropriate action. In most cases, this means a simple Namespace object will be built up from attributes parsed out of the command line:
ArgumentParser 通过 parse_args() 方法解析参数。它将检查命令行,把每个参数转换为适当的类型然后调用相应的操作。在大多数情况下,这意味着一个简单的 Namespace 对象将从命令行参数中解析出的属性构建:

parser.parse_args(['--sum', '7', '-1', '42'])
Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])

In a script, parse_args() will typically be called with no arguments, and the ArgumentParser will automatically determine the command-line arguments from sys.argv.
在脚本中,通常 parse_args() 会被不带参数调用,而 ArgumentParser 将自动从 sys.argv 中确定命令行参数。

invoke [ɪn'vəʊk]:vt. 调用,祈求,引起,恳求
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值