getopt – command line arguments in Python [Part 2]

getopt – command line arguments in Python [Part 2]

In the last article we learnt how to handle command line arguments in Python using sys.argv. We also noticed that it is not the ideal solution if your use case is a bit more complex. Now let’s see getopt,- a python module which builds on sys.argv. getopt provides us with features which make it easier to process command line arguments in Python.

We will be writing a simple python script to add or subtract two numbers and see how getopt is better than just using sys.argv.

Using getopt:

  • getopt is a module which comes bundled with any standard python installation and therefore you need not install it explicitly.
  • A major advantage of getopt over just using sys.argv is getopt supports switch style options ( Ex,-s or --sum).
  • Hence getopt supported options are position independent. Example $ ls -li works the same as $ ls -il
  • The options are of two types:
    • Options which need a value to be passed with them. These are defined by the option name suffixed with = (Ex, num1=)
    • Options which behave as a flag and do not need a value. These are defined by passing the option name without the suffix = (Ex, --subtract)
  • The options can have two variations:
    • shortopts are one letter options, denoted by prefixing a single - to an option name (Ex, $ ls -l)
    • longopts are a more descriptive representation of an option, denoted by prefixing two -- to an option name (Ex, $ ls --long-list)
  • As we saw in the sys.argv tutorial the options in getoptare always parsed asstring. So be careful if you want your input to have any other type. You may need to cast or convert the elements according to your requirements.

Output:

Explaining the code:

  • Our code prints the sum (addition) of the two numbers (-a and -b) but it can also print the difference between those numbers (subtraction) if you pass the flag --subtract or -s
    • getopt module provides a getopt(args, shortopts, longopts=[]) function which we can use to define our options.
    • sys.argv holds the unformatted list of all the arguments passed to a python script. Read more about it here.
    • We’re using two variables (opts, args) because getopt.getopt function returns two elements. One containing a <list> of options and another has a <list> of arguments which are not specified in our getopt initialisation.
    • You can specify shortopts as a colon(:) separated single letter characters.
    • You can specify longopts as a comma separated list of words with the suffix =
    • longopts without the suffix = are considered as a flag and they should be passed without any value.
  • Now, to use the options passed to our program we can just iterate over the opts variable like any other list.

    Here o will hold our option name and a will have any value assigned to the option. Also notice that as --subtract is being used as a flag it will not have any value. I am using this flag to decide whether to print the sum of the inputs or the difference in them.

So when should I use or not use getopt?

  • getopt provides an easy way to add switch like, position independent options in your script. You can quickly get up and running with it.
  • But getopts falls short if your requirements are a bit more specific, such as you need the arguments to be of certain data type or you need to make certain options mandatory. In such case you should take a look at argparse, Python’s recommended module for command-line argument parsing.

So what do you think? Please ask any questions you may have in the comment section below and be sure to check out Part 3 of this tutorial in a few days where I discuss about argparse in detail and you can also look into my Python and other Programming related tutorials.

P.S:

You can also consider making a small donation to support me. Your donation will directly contribute to the running cost of this website and hopefully my college too 🙂

Paypal: https://www.paypal.me/sapneshnaik | UPI: [email protected]

2
Leave a Reply

avatar
1 Comment threads
1 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Sapnesh NaikMarvin Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Marvin
Guest
Marvin

Nice tutorial.However,from trying it out and reading a couple of feeds online,the script should not be named getopt.py lst it return an – getopt’ module has no attribute ‘GetoptError – . To fix this if already run,remove the getopt.pyc file created upon first run and run the script under different name