Python Lib -- Argparse 命令行参数解析

How to -- argparse

步骤:

import argparse
# 收集命令行参数信息
parser = argparse.ArgumentParser(description="calculate X to the power of Y")
# 添加参数
parser.add_argument("x", type=int, help="the base")
# 返回已解析的参数
args = parser.parse_args()
print(args.x)

实例:

import argparse

parser = argparse.ArgumentParser(description="calculate X to the power of Y")

# 创建命令行参数组,两个参数互相排斥 [-v | -q]
group = parser.add_mutually_exclusive_group()
# 以 - 和 -- 命名的参数是,可选参数
# action="store_true" 表示当该可选参数出现时,它的值为 True ,否则,False
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")

# 不以连接符开头的参数为必须参数(位置参数) (require argument)
# type=int , 将值转换为 int 类型,默认为 string
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")

# 解析参数,将命令行参数作为 args 的属性, args.verbose
args = parser.parse_args()

# 以下是获取已解析的命令行参数
answer = args.x**args.y

if args.quiet:
    print(answer)
elif args.verbose:
    print("{} to the power {} equals {}".format(args.x, args.y, answer))
else:
    print("{}^{} == {}".format(args.x, args.y, answer))
Python Lib -- Argparse 命令行参数解析_第1张图片
arg.py

argparse 会自动生成 -h --help 及其他帮助信息

其他

限制参数的值

# choices:参数 -v 只能是列表中的值
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2], help="increase output verbosity")

统计参数出现的次数

# action='count' 返回参数出现的次数:-vvv (verbosity=3)
# 可用于显示信息的详细程度
parser.add_argument("-v", "--verbosity", action="count", help="increase output verbosity")

详细

https://docs.python.org/3/library/argparse.html#module-argparse

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)')

args = parser.parse_args()
print(args.accumulate(args.integers))
Python Lib -- Argparse 命令行参数解析_第2张图片
参数说明

ArgumentParser

ArgumentParser 最常用的参数是:description

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

add_augmemt

add_augment 用来定义如何解析一个参数
它接受的第一个位置参数是 name / flag:

  • 'integers' :name
  • '-v, --verbose' :flag

执行 args = parser.parse_args() 以上参数的值可以通过 args.integersargs.verbose 获取;

  • 可以通过参数 dest=sum 来表示该参数的值通过 args.sum 获取;
  • 默认,name / flag 也会显示在帮助信息中,可以通过 metavar 修改

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:

  • name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.
  • action - The basic type of action to be taken when this argument is encountered at the command line.
  • nargs - The number of command-line arguments that should be consumed.
  • const - A constant value required by some action and nargs selections.
  • default - The value produced if the argument is absent from the command line.
  • type - The type to which the command-line argument should be converted.
  • choices - A container of the allowable values for the argument.
  • required - Whether or not the command-line option may be omitted (optionals only).
  • help - A brief description of what the argument does.
  • metavar - A name for the argument in usage messages.
  • dest - The name of the attribute to be added to the object returned by parse_args().

你可能感兴趣的:(Python Lib -- Argparse 命令行参数解析)