Skip to content
Advertisement

Why is python getopt not parsing my options and instead think they are arguments?

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?

>> $ ipython
Python 2.7.6 (default, Nov 23 2017, 15:49:48) 
Type "copyright", "credits" or "license" for more information.

IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import getopt

In [2]: opts, args = getopt.getopt(['arg1', '-f', '-l'], "filo:t:", ["help", "output="])

In [3]: opts
Out[3]: []

In [4]: args
Out[4]: ['arg1', '-f', '-l']

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:

>>> import sys, getopt
>>> sys.version
'2.7.10 (default, Mar  8 2016, 15:02:46) [MSC v.1600 64 bit (AMD64)]'
>>>
>>> getopt.getopt(['arg1', '-f', '-l'], "filo:t:", ["help", "output="])
([], ['arg1', '-f', '-l'])
>>>
>>> getopt.getopt(['-f', '-l', 'arg1'], "filo:t:", ["help", "output="])
([('-f', ''), ('-l', '')], ['arg1'])

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:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement