getopt.getopt ( [命令行参数列表], '短选项', [长选项列表] )
短选项名后的冒号 : 表示该选项必须有附加的参数
长选项名后的等号 = 表示该选项必须有附加的参数返回 opts 和 argsopts 是一个参数选项及其value的元组 ( ( '-f', 'hello'), ( '-t', '' ), ( '--format', '' ), ( '--directory-prefix', '/home' ) )args 是一个除去有用参数外其他的命令行输入 ( 'a', 'b' )# 然后遍历 opts 便可以获取所有的命令行选项及其对应参数了
for opt, val in opts:if opt in ( '-f', '--format' ):passif ....使用字典接受命令行的输入,然后再传送字典,可以使得命令行参数的接口更加健壮
# 两个来自 python2.5 Documentation 的例子
# www.linuxidc.com>>> import getopt, sys>>> arg = '-a -b -c foo -d bar a1 a2'>>> optlist, args = getopt.getopt( sys.argv[1:], 'abc:d:' )>>> optlist[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]>>> args['a1', 'a2']>>> arg = '--condition=foo --testing --output-file abc.def -x a1 a2'>>> optlist, args = getopt.getopt( sys.argv[1:], 'x', ['condition=', 'output-file=', 'testing'] )>>> optlist[ ('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x','') ]>>> args['a1', 'a2']
getopt.getopt(args, shortopts, longopts=[])
Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this means sys.argv[1:]. shortopts is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (':'; i.e., the same format that Unix getopt() uses).
Note
Unlike GNU getopt(), after a non-option argument, all further arguments are considered also non-options. This is similar to the way non-GNU Unix systems work.
longopts, if specified, must be a list of strings with the names of the long options which should be supported. The leading '--'characters should not be included in the option name. Long options which require an argument should be followed by an equal sign ('='). Optional arguments are not supported. To accept only long options, shortopts should be an empty string. Long options on the command line can be recognized so long as they provide a prefix of the option name that matches exactly one of the accepted options. For example, if longopts is ['foo', 'frob'], the option --fo will match as --foo, but --f will not match uniquely, so will be raised.
The return value consists of two elements: the first is a list of (option, value) pairs; the second is the list of program arguments left after the option list was stripped (this is a trailing slice of args). Each option-and-value pair returned has the option as its first element, prefixed with a hyphen for short options (e.g., '-x') or two hyphens for long options (e.g., '--long-option'), and the option argument as its second element, or an empty string if the option has no argument. The options occur in the list in the same order in which they were found, thus allowing multiple occurrences. Long and short options may be mixed.