Python里的optparse

Python里的optparse是一个强大的命令行选项解析库

argument -- 参数

在命令行中输入的字符串,并会被 shell 传给 execl() 或 execv()

在 Python 中,参数将是 sys.argv[1:] 的元素

注:

  sys.argv[0] 是被执行的程序的名称

from optparse import OptionParser
#定义自己的用法消息
usage = "usage: %prog [options] arg1 arg2"
#开始定义选项,打印版本字符串
parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
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")
parser.add_option("-n", type="int", dest="num")

(options, args) = parser.parse_args()
if len(args) != 1:
    parser.error("incorrect number of arguments")
print(options)
print(options.filename)
#由解析选项之后余下的位置参数组成的列表
print(args)

说明:

  options 一个包含你所有的选项的值的对象

  args 由解析选项之后余下的位置参数组成的列表

  add_option里的

    type:输入命令行参数的值的类型,默认为string,可以为string, int, choice, float,complex

    default:命令参数的默认值

    metavar:帮助文档中显示提示用户输入期望的命令参数

    dest:指定参数在options对象中成员的名称

    help:在帮助文档中显示的信息

1.执行 python test.py

输出

Usage: test.py [-f] [-q]

test.py: error: incorrect number of arguments

2.执行python test.py -h

输出

Usage: test.py [-f] [-q]

Options:
--version show program's version number and exit
-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
-n NUM

3.执行python test.py aa

输出

{'filename': None, 'verbose': True, 'num': None}
None
['aa']

4.执行python test.py -n 3e

输出

Usage: test.py [-f] [-q]

test.py: error: option -n: invalid integer value: '3e'

5.执行python test.py -n 3 aa

输出

{'filename': None, 'verbose': True, 'num': 3}
None
['aa']

6.执行python test.py -f aa.txt -q aa

输出

{'filename': 'aa.txt', 'verbose': False, 'num': None}
aa.txt
['aa']

 

posted @ 2024-04-14 23:44  慕尘  阅读(10)  评论(0编辑  收藏  举报