Python解析命令行参数

使用Python编写应用程序或是脚本的时候,经常会用到命令行参数。C语言中有库函数getopt解析短命令行参数,使用getopt_long解析短命令和长命令的组合。

Python使用getopt模块,同时解析短命令和长命令。看具体使用例子

#!/usr/bin/python

import sys
import getopt

if __name__ == '__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'at:')
        print opts
        for opt, value in opts:
            if opt=='-a':
                print 'get option: %s' % (opt)
            elif opt=='-t':
                print 'get option %s and argstring %s' % (opt, value)
            else:
                print 'Invalid option: %s' % opt
    except getopt.GetoptError as e:
        print 'getopt error: ',
        print e

getopt方法根据我们提供的短命令和长命令字符串,解析命令行参数, 如果我们给定的命令行参数不在我们所给的命令集合中,抛出GetoptError异常。

在解析得到的(opt, value)对中, 参数选项是带有短横线的, 如'-a', '-t',但是在C语言getopt中,没有短横线。

猜你喜欢

转载自www.cnblogs.com/cppthomas/p/10131325.html