The Getopt module is used to extract command-line options and parameters, i.e. SYS.ARGV
command-line options make program parameters more flexible. Supports short and long option modes
For example python scriptname.py-f ' hello '--directory-prefix=/home-t--format ' a ' B '
Copy CodeThe code is 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 options ', [long list of options])
Colon after short option name: Indicates that the option must have additional parameters
The equal sign after the long option name = indicates that the option must have additional parameters
Return to opts and args
OPTs is a parameter option and its value tuple ('-f ', ' Hello '), ('-t ', '), ('--format ', '), ('--directory-prefix ', '/home ')
Args is a command-line input (' A ', ' B ') that removes useful arguments
Copy the Code code as follows:
# 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 the 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 ']