python 命令行参数解析

本文是从我另一个博客转载过来的,欢迎大家点击进去看一下,帮我增加点人气^_^

 

选择模块

根据python参考手册的提示,optparse 已经废弃,应使用 argparse

教程

概念

argparse 模块使用 add_argument 来添加可选的命令行参数,原型如下:

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(). 

上面的说明其实不用看,直接看示例好了:

仅仅想展示一些信息

# -*- coding: utf-8 -*-
"""
argparse tester
"""
import argparse

parser = argparse.ArgumentParser(description='argparse tester')

parser.add_argument("-v", "--verbose", help="increase output verbosity",
                    action="store_true")

args = parser.parse_args()

if args.verbose:
    print "hello world"

 

它会输出如下:

$ python t.py
$ python t.py -v
hello world
$ python t.py -h
usage: t.py [-h] [-v]

argparse tester

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  increase output verbosity

这里 -v 是这个选项的简写,--verbose 是完整拼法,都是可以的

help 是帮助信息,不解释了

args = parse_args() 会返回一个命名空间,只要你添加了一个可选项,比如 verbose,它就会把 verbose 加到 args 里去,就可以直接通过 args.verbose 访问。

如果你想给它起个别名,就需要在 add_argument 里加多一个参数 dest='vb'

这样你就可以通过 args.vb 来访问它了。

action="store_true" 表示该选项不需要接收参数,直接设定 args.verbose = True,

当然如果你不指定 -v,那么 args.verbose 就是 False

但如果你把 action="store_true" 去掉,你就必须给 -v 指定一个值,比如 -v 1

做个求和程序

# -*- coding: utf-8 -*-
"""
argparse tester
"""

import argparse

parser = argparse.ArgumentParser(description='argparse tester')

parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
parser.add_argument('numbers', type=int, help="numbers to calculate", nargs='+')
parser.add_argument('-s', '--sum', help="sum all numbers", action='store_true', default=True)


args = parser.parse_args()

print "Input:", args.numbers
print "Result:"
results = args.numbers

if args.verbose:
    print "hello world"

if args.sum:
    results = sum(args.numbers)
    print "tSum:tt%s" % results

输出如下:

[pan@pan-pc test]$ python t2.py -h
usage: t2.py [-h] [-v] [-s] numbers [numbers ...]

argparse tester

positional arguments:
  numbers        numbers to calculate

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  increase output verbosity
  -s, --sum      sum all numbers
[pan@pan-pc test]$ python t2.py 1 2 3 -s
Input: [1, 2, 3]
Result:
    Sum:        6

注意到这此可选项 numbers 不再加上 “-” 前缀了,因为这个是位置选项

如果把 nargs="+" 去掉,则只能输入一个数字。因为它指定了number 选项的值个数

如果把 type=int 去掉,则 args.numbers 就是一个字符串,而不会自动转换为整数

注意到 --sum 选项的最后还加上了 default=True,意思是即使你不在命令行中指定 -s,它也会默认被设置为 True

只能2选1的可选项

# -*- coding: utf-8 -*-
"""
argparse tester
"""

import argparse

parser = argparse.ArgumentParser(description='argparse tester')
#group = parser.add_mutually_exclusive_group()


parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
parser.add_argument('numbers', type=int, help="numbers to calculate", nargs='+')
parser.add_argument('-s', '--sum', help="sum all numbers", action='store_true', default=True)

parser.add_argument('-f', '--format', choices=['int', 'float'], help='choose result format', default='int')

args = parser.parse_args()

print "Input:", args.numbers
print "Result:"
results = args.numbers

if args.verbose:
    print "hello world"

if args.format == 'int':
    format = '%d'
else:
    format = '%f'

if args.sum:
    results = sum(args.numbers)
    print 'tsum:tt%s' % (format % results)

输出如下:

[pan@pan-pc test]$ python t2.py 1 2 3 -f float
Input: [1, 2, 3]
Result:
    sum:        6.000000
[pan@pan-pc test]$ python t2.py 1 2 3 -f double
usage: t2.py [-h] [-v] [-s] [-f {int,float}] numbers [numbers ...]
t2.py: error: argument -f/--format: invalid choice: 'double' (choose from 'int', 'float')

在添加选项 -f 时,传入了 choices=['int', 'float'] 参数,表示该选项只能从 int 或 float 中2选1

猜你喜欢

转载自panyanyany.iteye.com/blog/2226443