【Python】getopt - C 风格的命令行选项解析器

 

目录

一. 介绍

二. 说明

三. 实例

四. 参考


 

一. 介绍

getopt 模块是一个命令行选项解析器,其 API 设计会让 C getopt() 函数的用户感到熟悉。 不熟悉 C getopt() 函数或者希望写更少代码并获得更完善帮助和错误消息的用户应当考虑改用 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']

 

四. 参考

  1. https://docs.python.org/zh-cn/2.7/library/getopt.html

 

(完)

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值