Home  >  Article  >  Backend Development  >  Python命令行参数解析模块getopt使用实例

Python命令行参数解析模块getopt使用实例

WBOY
WBOYOriginal
2016-06-10 15:15:25924browse

格式

getopt(args, options[, long_options])

1.args表示要解析的参数.
2.options表示脚本要识别的字符.字符之间用”:”分隔,而且必须要以”:”后结尾,例如”a:b:c:”.
3.long_options是可选的,如果指定的话,可以解析长选项.形式为字符串列表,如[‘foo=', ‘frob='].长选项要求形式为”–name=value”
4.该方法返回2个元素.第一个元素是列表对, 对中第一个值是带有”-“或者”–”的选项名,第二个值是选项的值.第二个元素是options减去第一个元素的后的值,即不能识别的值.

如果要求只能解析长选项的话,options必须为空.只要指定了参数名,就必须传入参数,不支持可有可无的参数.

短选项实例

复制代码 代码如下:

import getopt

short_args = '-a 123 -b boy -c foo -d 2.3 unkown'.split()
print short_args

optlist, args = getopt.getopt(short_args, 'a:b:c:d:')
print optlist
print args


输出
复制代码 代码如下:

['-a', '123', '-b', 'boy', '-c', 'foo', '-d', '2.3', 'unkown']
[('-a', '123'), ('-b', 'boy'), ('-c', 'foo'), ('-d', '2.3')]
['unkown']

长选项实例
复制代码 代码如下:

import getopt

long_args = '--a=123 --b unkown'.split()
optlist, args = getopt.getopt(long_args, '', ['a=', 'b'])
print optlist
print args


输出
复制代码 代码如下:

[('--a', '123'), ('--b', '')]
['unkown']

长短选项结合实例
复制代码 代码如下:

import getopt

s = '--condition=foo --testing --output-file abc.def -x a1 unknown'
args = s.split()
optlist, args = getopt.getopt(args, 'x:', ['condition=', 'output-file=', 'testing'])
print optlist
print args


输出
复制代码 代码如下:

[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', 'a1')]
['unknown']
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn