Python模块之命令行参数解析

 转载https://www.cnblogs.com/madsnotes/articles/5687079.html

解析命令行参数模块

Python中由三个内建的模块用于处理命令行参数:
第一个:getopt,只能简单的处理命令行参数

官网资料:https://docs.python.org/2/library/getopt.html#module-getopt
第二个:optparse,功能强大,易于使用,可以方便地生成标准的、符合Unix/Posix 规范的命令行说明。(Python2.7以后弃用,不会继续发展)
官网资料:https://docs.python.org/2/library/optparse.html
第三个:argparse,使其更加容易的编写用户友好的命令行接口。它所需的程序进程了参数定义,argparse将更好的解析sys.argv。同时argparse模块还能自动生成帮助及用户输入错误参数时的提示信息。

官网资料:https://docs.python.org/2/library/argparse.html#module-argparse

getopt

   在运行程序时,可能需要根据不同的条件,输入不同的命令行选项来实现不同的功能。目前常用的由短选项和长选项两种格式。短选项格式为"-"加上单个字母 选项,长选项为"--"加上一个单词。长格式实在Linux下引入的。许多Linux程序都支持这两种格式。在Python中提供了getopt模块很好 的实现了对着两种用法的支持,而且使用简单。

获取命令行参数

Python环境下可以使用sys模块得到命令行参数

复制代码

import getopt
import sys

print(sys.argv)

C:\Users\Administrator\>python 222.py -o t --help cmd file1 file2
['222.py', '-o', 't', '--help', 'cmd', 'file1', 'file2']

# 由此可见,所有命令行参数以空格为分隔符,保存在sys.argv列表中,其中第一个为文件名

复制代码

选项的写法要求:
短格式:"-"号后面要紧跟一个选项字母。如果还有此选项的附加参数,可以用空格分开,也可以不分开。长度任意,可以用引号。
例如:
-o
-o "a b"
长格式:"--"号后面要跟一个单词。如果还有些选项的附加参数,后面要紧跟"=",再加上参数。"="号前后不能有空格。
例如:
--help=file1

如何使用getopt进行参数分析及处理?

第一步:导入sys,getopt模块
第二步:分析命令行参数
第三步:处理结果

复制代码

import getopt
import sys

# print(sys.argv)
def usage():
    print(
"""
Usage:sys.args[0] [option]
-h or --help:显示帮助信息
-m or --module:模块名称   例如:ansible all -m shell -a 'date'
-a or --args:模块对于的参数  例如:ansible all -m shell -a 'date'
-v or --version:显示版本
"""
    )
if len(sys.argv) == 1:
    usage()
    sys.exit()

try:
    opts, args = getopt.getopt(sys.argv[1:], "ho:m:a:", ["help", "output="])   # sys.argv[1:] 过滤掉第一个参数(它是脚本名称,不是参数的一部分)
except getopt.GetoptError:
    print("argv error,please input")

# 使用短格式分析串“ho:m:a:”
 当一个选项只表示开关状态时,即后面不带任何参数时,在分析串中写入选项字符,例如:-h表示获取帮助信息,显示完成即可,不需任何参数
 当一个选项后面需要带附加参数时,在分析串中写入选项字符同时后面加一个“:”号,例如:-m表示指定模块名称,后面需加模块名称

# 使用长格式分析串列表:["help", "output="]。
长格式串也可以有开关状态,即后面不跟"="号。如果跟一个等号则表示后面还应有一个参数。这个长格式表示"help"是一个开关选项;"output="则表示后面应该带一个参数。
# print(opts)
# print(args)
# 调用getopt函数。函数返回两个列表:opts和args。
# opts为分析出的格式信息,是一个两元组的列表。每个元素为:(选项串,附加参数)。如果没有附加参数则为空串''。
# args为不属于格式信息的剩余的命令行参数。
# 整个过程使用异常来包含,这样当分析出错时,就可以打印出使用信息来通知用户如何使用这个程序。

# 以下部分即根据分析出的结果做相应的处理,并将处理结果返回给用户
for cmd, arg in opts:  # 使用一个循环,每次从opts中取出一个两元组,赋给两个变量。cmd保存选项参数,arg为附加参数。接着对取出的选项参数进行处理。
    if cmd in ("-h", "--help"):
        print("help info")
        sys.exit()
    elif cmd in ("-o", "--output"):
        output = arg
    elif cmd in ("-m", "--module"):
        module_name = arg
    elif cmd in ("-a", "--module_args"):
        module_args = arg
    elif cmd in ("-v", "--version"):
        print("%s version 1.0" % sys.argv[0])

复制代码

案例2:获取用户信息,生成配置信息

argparse

 argparse简介

   argparse是Python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块。argparse模块的作用是用于解析 命 令行参数,例如python parseTest.py input.txt output.txt --user=name --port=8080。

argparse讲解

将以下代码保存为prog.py

复制代码

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')   # 首先创建一个ArgumentParser对象
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)')     # 添加--sum则返回所有数之和,否则返回列表中的最大值

args = parser.parse_args()
print args.accumulate(args.integers)

复制代码

复制代码

$ python prog.py -h
usage: prog.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)

# 输入正确的参数信息
$ python prog.py 1 2 3 4
4

$ python prog.py 1 2 3 4 --sum
10

# 输入错误的参数信息
$ python prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'

复制代码

ArgumentParser对象的参数
prog - The name of the program (default: sys.argv[0])
usage - The string describing the program usage (default: generated from arguments added to parser)
description - Text to display before the argument help (default: none)
epilog - Text to display after the argument help (default: none)
parents - A list of ArgumentParser objects whose arguments should also be included
formatter_class - A class for customizing the help output
prefix_chars - The set of characters that prefix optional arguments (default: ‘-‘)
fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None)
argument_default - The global default value for arguments (default: None)
conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)
add_help - Add a -h/–help option to the parser (default: True)
每个参数的详细说明:
prog:即运行程序的名称,默认取sys.argv[0]的值,可以修改为指定的名称
usage:指定usage信息的内容及格式,默认是根据你添加的信息自动生成的,可以自定义修改为指定的内容
description:这个程序的功能概述
epilog:在整个帮助信息最后添加的附加信息
parents:用于定义一些公共的信息供子类调用
formatter_class:整个信息的类定义,主要包含三个类,每个类的功能如下:
  • class argparse.RawDescriptionHelpFormatter # 如何显示文本描述
  • class argparse.RawTextHelpFormatter # 如何显示文本描述
  • class argparse.ArgumentDefaultsHelpFormatter # 自定添加参数信息
prefix_chars:自定义参数个前缀类型
fromfile_prefix_chars:指定文件替代命令行输入参数的方式
argument_default:
conflict_handler:检测是否存在相同的参数选项,不加该参数直接报错,添加该参数可以兼容(conflict_handler='resolve') 
add_help:  设置是否显示帮助信息那表之类(默认显示)

不设置该参数

设置该参数

add_argument()方法    

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

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

实际案例讲解

复制代码

# 基本认识,只有就基本框架
import argparse

parser = argparse.ArgumentParser()
parser.parse_args()

# 结果
C:\Users\Administrator\Desktop>python3 getopt_help.py -h
usage: getopt_help.py [-h]

optional arguments:
  -h, --help  show this help message and exit

C:\Users\Administrator\Desktop>python3 getopt_help.py foo
usage: getopt_help.py [-h]
getopt_help.py: error: unrecognized arguments: foo

C:\Users\Administrator\Desktop>python3 getopt_help.py -f
usage: getopt_help.py [-h]
getopt_help.py: error: unrecognized arguments: -f

# 结果分析
1)不给参数而运行这个程序,将不会得到任何结果
2)没有做任何特别设置,可以得到一个很简洁的帮助信息(第二三个例子)
3)无需人为设置--help参数,就能得到一个良好的帮助信息。但是若给其他参数(比如foo)就会产生一个错误。

复制代码

 其他

 if len(sys.argv) == 1:
     parser.print_help()
     sys.exit(1)

出处:http://www.cnblogs.com/madsnotes/

声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。

猜你喜欢

转载自blog.csdn.net/chqj_163/article/details/89397301