Python getopt模块处理命令行选项实例
2014-05-13 00:00
951 查看
getopt模块用于抽出命令行选项和参数,也就是sys.argv
命令行选项使得程序的参数更加灵活。支持短选项模式和长选项模式
例如 python scriptname.py -f 'hello' --directory-prefix=/home -t --format 'a' 'b'
getopt.getopt ( [命令行参数列表], '短选项', [长选项列表] )
短选项名后的冒号 : 表示该选项必须有附加的参数
长选项名后的等号 = 表示该选项必须有附加的参数
返回 opts 和 args
opts 是一个参数选项及其value的元组 ( ( '-f', 'hello'), ( '-t', '' ), ( '--format', '' ), ( '--directory-prefix', '/home' ) )
args 是一个除去有用参数外其他的命令行输入 ( 'a', 'b' )
使用字典接受命令行的输入,然后再传送字典,可以使得命令行参数的接口更加健壮
# 两个来自 python2.5 Documentation 的例子
命令行选项使得程序的参数更加灵活。支持短选项模式和长选项模式
例如 python scriptname.py -f 'hello' --directory-prefix=/home -t --format 'a' 'b'
import getopt, sys shortargs = 'f:t' longargs = ['directory-prefix=', 'format'] opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )
getopt.getopt ( [命令行参数列表], '短选项', [长选项列表] )
短选项名后的冒号 : 表示该选项必须有附加的参数
长选项名后的等号 = 表示该选项必须有附加的参数
返回 opts 和 args
opts 是一个参数选项及其value的元组 ( ( '-f', 'hello'), ( '-t', '' ), ( '--format', '' ), ( '--directory-prefix', '/home' ) )
args 是一个除去有用参数外其他的命令行输入 ( 'a', 'b' )
# 然后遍历 opts 便可以获取所有的命令行选项及其对应参数了 for opt, val in opts: if opt in ( '-f', '--format' ): pass if ....
使用字典接受命令行的输入,然后再传送字典,可以使得命令行参数的接口更加健壮
# 两个来自 python2.5 Documentation 的例子
>>> import getopt, sys >>> arg = '-a -b -c foo -d bar a1 a2' >>> optlist, args = getopt.getopt( sys.argv[1:], 'abc:d:' ) >>> optlist [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] >>> args ['a1', 'a2'] >>> arg = '--condition=foo --testing --output-file abc.def -x a1 a2' >>> optlist, args = getopt.getopt( sys.argv[1:], 'x', ['condition=', 'output-file=', 'testing'] ) >>> optlist [ ('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x','') ] >>> args ['a1', 'a2']
相关文章推荐
- Python getopt模块处理命令行选项实例
- Python命令行选项处理模块Getopt使用
- 使用getopt模块处理命令行选项
- Python 有两个内建的模块(getopt,optparse)用于处理命令行参数
- 命令行參数选项处理:getopt()及getopt_long()函数使用
- python采用getopt解析命令行输入参数实例
- 【python】详解zipfile模块读取处理压缩文件实例
- Python:使用getopt模块处理命令行参数
- python中 命令行参数处理 --getopt 模块
- Python命令行参数解析模块getopt使用实例
- getopt:命令行选项、参数处理
- 使用getopt模块获取命令行选项
- perl模块Getopt::Std用法及实例-从命令行读取参数模块
- getopt/getopts:Bash中命令行选项/参数处理
- 使用Getopt::Long来处理复杂的命令行选项
- python模块学习---getopt(命令行参数处理)
- python argparse模块解析命令行选项简单使用
- 实例讲解Python中SocketServer模块处理网络请求的用法
- python采用getopt解析命令行输入参数实例
- getopt 模块:命令行选项和参数的函数