The Python getopt module handles instances of command line options

  • 2020-04-02 13:38:15
  • OfStack

The getopt module is used to extract command-line options and parameters, i.e. Sys. argv
Command-line options make the program's arguments more flexible. Support short option mode and long option mode
For example,   Python scriptname. py-f 'hello' --directory prefix=/ home-t --format 'a' 'b'


import getopt, sys
shortargs = 'f:t'
longargs = ['directory-prefix=', 'format']
opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )

Getopt. getopt ([list of command line arguments], 'short options ', [list of long options])

Colon after short option name: indicates that the option must have additional arguments
An equal sign after a long option name = indicates that the option must have additional parameters

Returns opts and args
Opts is a parameter option and the value of a tuple ((' -f ', 'hello'), (' - t ', '), (' -- the format ', '), (' - directory - the prefix ', '/ home'))
Args is a command line input except for useful arguments ('a', 'b')    

#  Then traverse  opts  You can get all the command line options and their corresponding arguments 
for opt, val in opts:
    if opt in ( '-f', '--format' ):
        pass
    if ....

Using a dictionary to take command line input and then pass the dictionary makes the interface for command line arguments more robust

Two examples from python2.5 Documentation


>>> 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']


Related articles: