I am attempting to use python’s getopt to parse some input arguments, but my options are not recognised. Why does the following happen? What am I doing wrong?
JavaScript
x
20
20
1
>> $ ipython
2
Python 2.7.6 (default, Nov 23 2017, 15:49:48)
3
Type "copyright", "credits" or "license" for more information.
4
5
IPython 1.2.1 -- An enhanced Interactive Python.
6
? -> Introduction and overview of IPython's features.
7
%quickref -> Quick reference.
8
help -> Python's own help system.
9
object? -> Details about 'object', use 'object??' for extra details.
10
11
In [1]: import getopt
12
13
In [2]: opts, args = getopt.getopt(['arg1', '-f', '-l'], "filo:t:", ["help", "output="])
14
15
In [3]: opts
16
Out[3]: []
17
18
In [4]: args
19
Out[4]: ['arg1', '-f', '-l']
20
Advertisement
Answer
According to [Python2.Docs]: getopt.getopt(args, options[, long_options]) (emphasis is mine):
Note: Unlike GNU
getopt()
, after a non-option argument, all further arguments are considered also non-options. This is similar to the way non-GNU Unix systems work.
arg1 is such a non-option argument. Placing it at the end of the list (the 2nd call), would yield the expected output:
JavaScript110101>>> import sys, getopt
2>>> sys.version
3'2.7.10 (default, Mar 8 2016, 15:02:46) [MSC v.1600 64 bit (AMD64)]'
4>>>
5>>> getopt.getopt(['arg1', '-f', '-l'], "filo:t:", ["help", "output="])
6([], ['arg1', '-f', '-l'])
7>>>
8>>> getopt.getopt(['-f', '-l', 'arg1'], "filo:t:", ["help", "output="])
9([('-f', ''), ('-l', '')], ['arg1'])
10
From the same page (what @tripleee also suggested):
Note that an equivalent command line interface could be produced with less code and more informative help and error messages by using the argparse module: