python模块之--optparse
2012-04-11 12:34
225 查看
optparse是用来在命令行添加选项的模块,简单命令行参数可以使用sys.argv
来实现,对于复杂的命令行参数使用optparse模块会更加方便
示例代码:opt.py
运行python opt.py -F 2 bob, 输出选项和参数的值 如下
运行python opt.py -h, 输出帮助信息如下
步骤:
1、产生OptionParser的对象parser。并传入usage信息生成帮助信息的Usage部分
2、调用OptionParser.add_option函数,添加选项
add_option()的参数说明
首先是长短选项 -F和--from
action:存储方式,分为三种store,store_false,store_true
详细分析:
1)action="store"默认值,将命令行选项后面的值(示例中-F 2)和dest的值(from_step)组成字典({'from_step':2})并赋值给options,所以options.from_step的值为2
2)action="store_true",options.from_step的值是Ture,不是2
3)action="store_false",options.from_step的值是False,不是2
type:参数类型
dest:存储的变量,即生成字典的key
default:设置参数的默认值
help:帮助信息
metavar:帮助信息中用到
3、调用OptionParser的parse_args函数生成字典和列表
options是一个字典(带选项的参数组成),args是一个列表(不带选项的参数组成)
此外:调用OptionParser的print_help()函数会输出帮助信息
来实现,对于复杂的命令行参数使用optparse模块会更加方便
示例代码:opt.py
#!/usr/bin/env python import optparse usage = "%prog [-F <from_step>]" parser = optparse.OptionParser(usage) parser.add_option("-F","--from",dest="from_step",default=1,type="int",help="the from step,default 1",metavar="FROM_STEP") (options,args) = parser.parse_args() print "options:%s" % options print "args:%s" % args print "from_step:%s" % options.from_step
运行python opt.py -F 2 bob, 输出选项和参数的值 如下
options:{'from_step': 2} args:['bob'] from_step:2
运行python opt.py -h, 输出帮助信息如下
Usage: opt.py [-F <from_step>] Options: -h, --help show this help message and exit -F FROM_STEP, --from=FROM_STEP the from step,default 1
步骤:
1、产生OptionParser的对象parser。并传入usage信息生成帮助信息的Usage部分
usage = "%prog [-F <from_step>]" parser = optparse.OptionParser(usage)
2、调用OptionParser.add_option函数,添加选项
parser.add_option("-F","--from",dest="from_step", default=1,type="int",help="the from step, default 1,metavar="FROM_STEP")
add_option()的参数说明
首先是长短选项 -F和--from
action:存储方式,分为三种store,store_false,store_true
详细分析:
1)action="store"默认值,将命令行选项后面的值(示例中-F 2)和dest的值(from_step)组成字典({'from_step':2})并赋值给options,所以options.from_step的值为2
2)action="store_true",options.from_step的值是Ture,不是2
3)action="store_false",options.from_step的值是False,不是2
type:参数类型
dest:存储的变量,即生成字典的key
default:设置参数的默认值
help:帮助信息
metavar:帮助信息中用到
3、调用OptionParser的parse_args函数生成字典和列表
(options,args) = parser.parse_args()
options是一个字典(带选项的参数组成),args是一个列表(不带选项的参数组成)
此外:调用OptionParser的print_help()函数会输出帮助信息
相关文章推荐
- Python模块学习——optparse
- python模块学习---optparse
- Python模块学习——optparse
- Python模块学习——optparse
- Python:模块optparse
- Python模块学习——optparse
- Python模块学习——optparse (详细)
- python optparse模块使用实例
- 【Python 命令行参数解析: optparse 模块】
- Python--模块之optparse
- python模块整理24-Optparse选项参数
- Python模块学习——optparse
- Python模块学习——optparse
- Python模块整理(七):选项模块Optparse
- python命令行参数处理模块 optparse 使用参考
- Python之命令解析模块optparse
- Python模块学习——optparse
- 转载---Python模块学习optparse 处理命令行参数
- Python模块学习——optparse
- Python模块学习——optparse