使用Python编写应用程序或是脚本的时候,常常会用到命令行参数。C语言中有库函数getopt解析短命令行参数,使用getopt_long解析短命令和长命令的组合。python
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异常。spa
在解析获得的(opt, value)对中, 参数选项是带有短横线的, 如'-a', '-t',可是在C语言getopt中,没有短横线。命令行