目录
一. 介绍
getopt
模块是一个命令行选项解析器,其 API 设计会让 Cgetopt()
函数的用户感到熟悉。 不熟悉 Cgetopt()
函数或者希望写更少代码并获得更完善帮助和错误消息的用户应当考虑改用argparse
模块。
二. 说明
代码资源:
’Lib/getopt.py’
此模块提供了两个函数和一个异常;
getopt.getopt(args, options[, long_options])
args:命令行输入的参数列表,典型场景一般为: sys.argv[1:]
options:脚本要识别的选项字符串,一般后面跟个':',表示该选项必须有附加的参数
返回值由两个元素组成:
第一个是 (option, value)
对的列表;
第二个是在去除该选项列表后余下的程序参数列表(这也就是 args 的尾部切片)。每个被返回的选项与值对的第一个元素是选项,短选项前缀一个连字符 (例如 '-x'
),长选项则前缀两个连字符 (例如 '--long-option'
),第二个元素是选项参数,如果选项不带参数则为空字符串。 列表中选项的排列顺序与它们被解析的顺序相同,因此允许多次出现。 长选项与短选项可以混用。
三. 实例
# -- coding:utf-8 --
import getopt
import sys
# reload(sys)
# sys.setdefaultencoding('utf8')
def test_getopts():
'''
getopt函数的格式是getopt.getopt ( [命令行参数列表], "短选项", [长选项列表] )
短选项名后的冒号(:)表示该选项必须有附加的参数。
长选项名后的等号(=)表示该选项必须有附加的参数。
'''
short_opt = 'c:d' # 短链选项
long_args = ['info', 'debug', 'time='] # 长链选项
print
sys_argv = sys.argv[1:]
print 'the current sys_argv: %s' % sys_argv
print
opts, args = getopt.getopt(sys_argv, short_opt, long_args)
print('the current opts type: %s' % type(opts))
print('the current opts = %s' % opts)
print('the current opts[0] type: %s' % type(opts[0]))
print
print('the current args type: %s' % type(args))
print('the current args = %s' % args)
print
def debug_print_command():
'''
命令输入,测试数据:
1. python test_getopts.py -c c_args:c -d d start_date=2019 end_date=2020
2. python test_getopts.py -c c_args:c -d start_date=2019 end_date=2020
3. python test_getopts.py -c c_args:c -d --info start_date=2019 end_date=2020
4. python test_getopts.py -c c_args:c -d --debug --time=the_current_system_time start_date=2019 end_date=2020
'''
argv = [
'python', 'test_getopts.py', '-c', 'c_args:c', '-d', 'd',
'start_date=2019', 'end_date=2020'
]
print " ".join(argv)
if __name__ == "__main__":
'''主函数入口'''
test_getopts()
# debug_print_command()
输入如下命令:
python test_getopts.py -c c_args:c -d d start_date=2019 end_date=2020
输出如下所示:
$ python test_getopts.py -c c_args:c -d d start_date=2019 end_date=2020
the current sys_argv: ['-c', 'c_args:c', '-d', 'd', 'start_date=2019', 'end_date=2020']
the current opts type: <type 'list'>
the current opts = [('-c', 'c_args:c'), ('-d', '')]
the current opts[0] type: <type 'tuple'>
the current args type: <type 'list'>
the current args = ['d', 'start_date=2019', 'end_date=2020']
四. 参考
(完)