代码如下

#!/usr/bin/python
from optparse import OptionParser
usage = 'python %prog -f [filename] -q'
parser = OptionParser(usage)
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")
(options, args) = parser.parse_args()
print options.filename,options.verbose

1、python test.py

结果:None True

2、python test.py -f

结果:Usage: usage test.py -f [filename] -q

test.py: error: -f option requires an argument

3、python test.py -f file

结果:file True

4、python test.py -q

结果:None False

5、python test.py -h

结果:Usage: usage test.py -f [filename] -q

Options:
  -h, --help            show this help message and exit
  -f FILE, --file=FILE  write report to FILE
  -q, --quiet           don't print status messages to stdout

分析说明:
parser = OptionParser() 可自定义usage的格式,默认是“Usage:test.py [option]”

add_option用来加入选项

action是有store,store_true,store_false等

dest是存储的变量,

default是缺省值

help是帮助提示

最后通过parse_args()函数的解析,获得选项,如options.fileName,options.verbose


Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐