The following is an example of how the Python getopt module processes command line options.
In python programming, the getopt module is as flexible and practical as the getopt parameter module in shell.
The getopt module is used to extract command line options and parameters, that is, sys. argv
The command line option makes program parameters more flexible. Supports short and long options.
For example
python scriptname.py -f 'hello' --directory-prefix=/home -t --format 'a' 'b'import getopt, sysshortargs = 'f:t'longargs = ['directory-prefix=', 'format']opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )
Getopt. getopt ([command line parameter list], 'short options', [long optionlist])
Colon after short option name: indicates that this option must have additional parameters
Equal Sign = after long option name indicates that this option must have additional parameters
Returns opts and args
Opts is a parameter option and its value tuples ('-F', 'Hello'), ('-t', ''), ('-- format ', ''), ('-- directory-prefix','/home '))
Args is a command line input ('A', 'B') that removes useful parameters ')
# Then traverse opts to obtain all command line options and their corresponding parameters with the for opt, val in opts: if opt in ('-F',' -- format '): passif ....
Use the dictionary to accept the input of the command line and then transmit the dictionary, which makes the interface of the command line parameters more robust.
# Two examples from python2.5 Documentation # www.jbxue.com >>> 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 ']