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:
1 2 3 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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:
- In
sys.argv[1:]
, we are using starting index as 1 assys.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 fromsys.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:
1 2 3 4 5 6 7 8 |
-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:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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