Parsing command line arguments is a very common task, python getopt module is one of the option to parse python command line arguments.
Table of Contents
- 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:
argsare the arguments to be passed.
shortoptsis the options this script accepts.
- Optional parameter,
longoptsis 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:] try: opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file=']) print(opts) print(args) except getopt.GetoptError: #Print a message or do something useful print('Something went wrong!') sys.exit(2)
In this example, we simply accepted some arguments. Before running the script, let’s establish our understanding on what happened here:
sys.argv[1:], we are using starting index as 1 as
sys.argvis 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
getoptcall, 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:
-h print help and usage message -m: accept custom option value -d 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:
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:
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
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:
We can even try running this script without any arguments:
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