Format
Getopt (args, options[, long_options])
1.args represents the parameters to resolve.
2.options indicates the character to be recognized by the script. The characters are delimited by ":" and Must End with ":", such as "A:B:C:".
3.long_options is optional, and if specified, the long option can be resolved. The form is a list of strings, such as [' foo= ', ' frob= ']. Long options require the form "–name=value"
4. The method returns 2 elements. The first element is a list pair, with the first value being the option name with "-" or "–", and the second value being the value of the option. The second element is the options minus the value after the first element, which is the unrecognized value.
If you require only long options to be resolved, the options must be empty. Parameters must be passed in as long as the parameter name is specified, and no optional arguments are supported.
Short option Instance
Copy Code code as follows:
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
Output
Copy Code code as follows:
['-a ', ' 123 ', ' B ', ' Boy ', '-C ', ' foo ', '-d ', ' 2.3 ', ' unkown ']
[('-a ', ' 123 '), ('-B ', ' Boy '), ('-C ', ' Foo '), ('-d ', ' 2.3 ')]
[' Unkown ']
Long Option Instance
Copy Code code as follows:
Import getopt
Long_args = '--a=123--b unkown '. Split ()
Optlist, args = getopt.getopt (Long_args, ', [' a= ', ' B '])
Print Optlist
Print args
Output
Copy Code code as follows:
[('--a ', ' 123 '), ('--b ', ')]
[' Unkown ']
length options combined with instances
Copy Code code as follows:
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
Output
Copy Code code as follows:
[('--condition ', ' foo '), ('--testing ', '), ('--output-file ', ' Abc.def '), (' X ', ' A1 ')]
[' Unknown ']