The Getopt module is used to extract command-line options and parameters, i.e. SYS.ARGV
command-line options make the program more flexible in its parameters. Supports short option mode and long option mode
For example python scriptname.py-f ' hello '--directory-prefix=/home-t--format ' a ' B '
Copy Code code as follows:
Import getopt, sys
Shortargs = ' F:t '
Longargs = [' directory-prefix= ', ' format ']
opts, args = Getopt.getopt (sys.argv[1:], Shortargs, Longargs)
getopt.getopt ([command line argument list], ' short option ', [long option list]]
Colon after short option name: Indicates that the option must have additional parameters
The equals sign after the long option name = indicates that the option must have additional parameters
Back to opts and args
OPTs is a tuple of parameter options and their value ('-f ', ' Hello '), ('-t ', ', '), ('--format ', '), ('--directory-prefix ', '/home '))
Args is a command line input other than a useful parameter (' A ', ' B ')
Copy Code code as follows:
# and then traverse opts to get all the command-line options and their corresponding parameters.
For opt, Val in opts:
If opt in (' f ', '--format '):
Pass
If .....
Use a dictionary to accept command-line input and then transfer the dictionary to make the interface of command-line arguments more robust
# Two examples from python2.5 documentation
Copy Code code as follows:
>>> 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 ']