The Python command line parameter parsing module getopt USES instances
- 2020-05-09 18:45:30
- OfStack
format
getopt(args, options[, long_options])
1.args represents the parameter to be parsed.
2.options represents the character to be recognized by the script. Characters are separated by ":" and must end with ":", for example, "a:b:c:".
3.long_options is optional, and long options can be parsed if specified in the form of a list of strings such as [' foo=', 'frob='].
The first element is the list pair, the first value is the option name with "-" or "wok", the second value is the option value, the second element is the value of options minus the first element, that is, the unrecognized value.
If you want to parse only long options,options must be null. As long as you specify a parameter name, you must pass in the parameter, not support optional arguments.
Short option instance
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
The output
['-a', '123', '-b', 'boy', '-c', 'foo', '-d', '2.3', 'unkown']
[('-a', '123'), ('-b', 'boy'), ('-c', 'foo'), ('-d', '2.3')]
['unkown']
Long option instance
import getopt
long_args = '--a=123 --b unkown'.split()
optlist, args = getopt.getopt(long_args, '', ['a=', 'b'])
print optlist
print args
The output
[('--a', '123'), ('--b', '')]
['unkown']
Long and short options combined with the example
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
The output
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', 'a1')]
['unknown']