getopt是python3中按C语言的格式来进行参数选项的处理模块。

getopt能够处理短选项和长选项: -a  短选项 --add 长选项

处理过程分为三步:

第一步先取得要处理的选项集字符串 import sys args = sys.argv[1:]

第二步调用方式 getopt.getopt(args,'hvo:') 短选项 getopt.getopt(args,(hvo:),['help', 'version', 'output=']) 长短选项 如果只要长选项,可以把短选项改成''字符串 说明 args 为选项集字符串 'hvo:' 为短选项处理格式,h,v,都表示是为无参数,o:表示必有参数,必须要有参数的则在字符后面加“:”表示. ['help', 'version', 'output='] 为长选项处理格式,help,version都表示为无参数,output=表示为必有参数,表达工里需要在字符串后加 "=" 表示。 看官网的列子: 短选项例子

import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']

长选项例子

>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = s.split()
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'x', [
...     'condition=', 'output-file=', 'testing'])
>>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
>>> args
['a1', 'a2']

getopt.getopt()返回两个值, 一个为optlist,参数选项和参数值组成的一个列表     一个为args,单独的参数值组成一个列表对应参数选项 写的时间需注意要匹配的参数和参数值要写在前面,不然会出现意外。 如

import sys
import getopt
args = '-a -b -cfoo -d bar a1 a2 a3'.split()
print(args)
optlist,arg = getopt.getopt(args,'abc:d:')
print('optlist:')
print(optlist)
print('arg:')
print(arg)
输出
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
optlist:
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
arg:
['a1', 'a2']
正常
如果把args改成args = '-a -b -cfoo xxx -d bar a1 a2 a3'.split()
['-a', '-b', '-cfoo', 'xxx', '-d', 'bar', 'a1', 'a2']
optlist:
[('-a', ''), ('-b', ''), ('-c', 'foo')]
arg:
['xxx', '-d', 'bar', 'a1', 'a2']这样会把-d选项当成一个对无应参数选项的参数值。
长选项处理过程一样
args为:'-h -o file --help --output=out file1 file2'
在处理完成后,optlist应该是:
[('-h', ''), ('-o', 'file'), ('--help', ''), ('--output', 'out')]
而args则为:
['file1', 'file2']

第三步为对分析出的参数进行处理 主要使用

for o,v in optlist:
    if o in ("-h","--help"):
        usage()
        sys.exit()
    if o in ("-o", "--output"):
        output = v
使用循环,从optlist中取出一个两元组,赋给两个变量。o保存选项参数,v为参数值。接着对取出的选项参数进行处理。
你可能感兴趣的内容
0条评论

dexcoder

这家伙太懒了 <( ̄ ﹌  ̄)>
Owner