Python之getopt模块

1、getopt——C风格命令行解析

http://docs.python.org/2.7/library/getopt.html#module-getopt

getopt.getopt(args, options[, long_options])

 先引入一个例子:

>>> import getopt
>>> 
>>> args = "-a -b -cfoo -d bar a1 a2".split() #将输入的参数转换成一个列表,通常在实例应用中args = sys.argv[1:]
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist,args = getopt.getopt(args,'abc:d:') #abc:d:,说明a和b只是是否有该选项,但是后面不跟值,而c和d不同,后面是有值的,故以冒号(:)区分
>>> 
>>> optlist #获取到参数以及对应的值
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args #-d后续只跟一个值,故a1和a2当做参数
['a1', 'a2']

上面的例子是短选项模式,下面再举个长选项模式的例子:

>>> import getopt
>>> 
>>> s = "--condition=foo --testing --output-file abc.def -a foo -x a1 a2" #长选项和短选项结合,-x和-a是短选项,其他都是长选项
>>> 
>>> args = s.split()
>>> 
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-a', 'foo', '-x', 'a1', 'a2']
>>> 
>>> optlist,args = getopt.getopt(args,'x','a',['condition=','output-file=','testing'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: getopt() takes at most 3 arguments (4 given)
>>> 
>>> optlist,args = getopt.getopt(args,'xa:',['condition=','output-file=','testing'])   #getopt.getopt()函数接受三个参数,第一个是所有参数输入,第二个是短选项,第三个是长选项
>>> 
>>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-a', 'foo'), ('-x', '')]
>>> args
['a1', 'a2']

getopt模块用于抽出命令行选项和参数,也就是sys.argv。命令行选项使得程序的参数更加灵活。支持短选项模式和长选项模式。

getopt函数的格式是getopt.getopt ( [命令行参数列表], "短选项", [长选项列表] )

 返回两个参数optlist,args

optlist是一个参数以及对应的vaule构成的元组

args是除了参数外其他的命令输入

然后遍历optlist便可以获取所有的命令行以及对应参数:

>>> for opt,val in optlist:
...     if opt in ('-a','--a_long'):
...             pass
...     if opt in (xxx)

使用字典接受命令行的输入,然后再传送字典,可以使得命令行参数的接口更加健壮。

 python文档中给出使用方法:

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

import getopt
import sys
def usage():
        help_msg = '''Usage:./test_opt.y [option] [value]...
        -h --help  show help
        -o --output output file
        -v verbose'''

        print help_msg

def main():
        if len(sys.argv) == 1:
                usage()
                sys.exit()
        try:
                opts,args = getopt.getopt(sys.argv[1:],'ho:v',["help","output="])
        except getopt.GetoptError as err:
                print str(err)
                sys.exit(2)
        except Exception,e:
                print e

        output = None
        verbose = False


        for opt,arg in opts:
                if opt == "-v":
                        verbose = True
                elif opt in ("-h","--help"):
                        usage()
                        sys.exit()
                elif opt in ("-o","--output"):
                        output = arg
                else:
                        assert False,"unhandled option"
if __name__ == "__main__":
        main()

 

2、argparse——python2.7中新添加的

http://docs.python.org/2.7/library/argparse.html#module-argparse

http://www.cnblogs.com/lovemo1314/archive/2012/10/16/2725589.html

原文地址:https://www.cnblogs.com/gsblog/p/3375710.html