Python getopt

Filed Under: Python

Parsing command line arguments is a very common task, python getopt module is one of the option to parse python command line arguments.

Python getopt

  • Python getopt module is very similar in working as the C getopt() function for parsing command-line parameters.
  • As this function is similar to C function and Unix getopt() function, users familiar with those conventions will find it very easy to use Python getopt module functions.

If you want a simpler module to parse command-line parameters, try argparse.

Python getopt function

getopt is the first function provided by the module with same name.

It parses the command line options and parameter list. The signature of this function is mentioned below:

getopt.getopt(args, shortopts, longopts=[])

Its arguments includes:

  • args are the arguments to be passed.
  • shortopts is the options this script accepts.
  • Optional parameter, longopts is the list of String parameters this function accepts which should be supported. Note that the -- should not be prepended with option names.

Let us study this function using some examples.

Python getopt example

Now this will be tricky at first glance. We will see a simple example which will be tricky but we will explain things afterwards.

Here is the code snippet:

import getopt
import sys

argv = sys.argv[1:]
    opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
except getopt.GetoptError:
    #Print a message or do something useful
    print('Something went wrong!')

In this example, we simply accepted some arguments. Before running the script, let’s establish our understanding on what happened here:

  • In sys.argv[1:], we are using starting index as 1 as sys.argv[0] is the name of the script that we’re running which we need not access in our script.
  • Now, the getopt function takes in three parameters:
    the command-line argument list which we get from sys.argv[1:], a string containing all accepted single-character command-line options that the script accepts, and a list of longer command-line options that are equivalent to the single-character versions.
  • If anything wrong happens with the getopt call, we can also catch the Exception and handle it gracefully. Here, we just exited the script execution.
  • As in any other commands in any operating system, it is wise to print details when a user runs a script incorrectly.

So, what does the hm:d means? See here:

  print help and usage message
  accept custom option value
  run the script in debug mode

The first and last options are defaults. We use a custom option as m:, notice the colon? Colon means that this option can get any type of value. Finally, the single-character versions are same as longer versions, h is same as help. You can mention any one.

Let’s run the script now:
Python getopt example, python command line arguments

So, this collected the options and arguments in separate lists. The best part about getopt is that it allows us to gracefully manage any possible exceptions:
python getopt error

About the my_file= flag, there is an important point to note. The my_file= flag must always be provided with an additional argument, exactly like the -m flag. This is described by an equals sign in my_file=.

Python gnu_output() for GNU style Parsing

In Python 2.3, another function was added in getopt module called gnu_output(). This function is very similar to the original getopt() function except the fact that by default, GNU style scanning is used. Let’s see an example script on how to use this function:

import getopt
import sys

variant = '1.0'
debug = False
output_file = 'my_file.out'

print('ARGV      :', sys.argv[1:])

options, remainder = getopt.gnu_getopt(
    sys.argv[1:], 'o:v', ['output=', 'debug', 'variant=',])
print('OPTIONS   :', options)

for opt, arg in options:
    if opt in ('-o', '--output'):
        print('Setting --output.')
        output_file = arg
    elif opt in ('-d', '--debug'):
        print('Setting --debug.')
        debug = True
    elif opt == '--variant':
        print('Setting --variant.')
        variant = arg

print('VARIANT   :', variant)
print('DEBUG   :', debug)
print('OUTPUT    :', output_file)
print('REMAINING :', remainder)

Before we establish an understanding, let’s run this script:
Python getopt GNU Output

We can even try running this script without any arguments:
Python getopt GNU Output No argument

This describes default values which are assigned to values when no arguments are passed.

Don’t forget to try the argparse module if you want more flexibility.

In this lesson, we learned about various ways through which we can manage the command-line parameters with getopt module in Python.

Reference: API Doc

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages