optparse模块使用

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

# python中有两个内建模块用来处理命令行参数:getpot、optparse。
# optparse模块主要用来为脚本传递命令参数,采用预定义好的选项来解析命令行参数。

# add_option()参数说明:
# action  存储方式,分为三种store、store_false、store_true
# type    类型
# dest    存储的变量
# default 默认值
# help    帮助信息

from optparse import OptionParser

def option():
    #创建一个parser对象
    parser = OptionParser()
    #增加一个选项
    parser.add_option("-f", "--file", action="store", type="string", dest="filename", help="config file")
    parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="exit")
    options, args = parser.parse_args()
    #获取参数的办法是options.变量名称,在desc=“”指定。
    print(options.filename)

option()

 

# python3 optparse模块.py --help
Usage: optparse模块.py [options]

Options:
  -h, --help            show this help message and exit
  -f FILENAME, --file=FILENAME
                        config file
  -q, --quiet           exit


# python3 optparse模块.py -f /etc/my.cnf 
/etc/my.cnf

 

posted @ 2022-09-02 16:53  捧花大王  阅读(109)  评论(0编辑  收藏  举报