Generic selectors
Exact matches only
Search in title
Search in content
wb_sunny

Command Line Arguments – getopt module

Getopt module Line Option Parser

Hey folks! In this article, we will understand the getopt module which supports command line arguments. So, let’s get started.

What is the getopt module?

The getopt module is a parser for command-line arguments that supports the same functionality as the Unix getopt() function. Its API is designed similar to the C getopt() function.

In the demonstrations that follow, we’ll use the sys module to read arguments passed to the program using the sys.argv function and then use the getopt module to parse the arguments.

  • sys.argv : List of command-line arguments
  • len(sys.argv): Number of command-line arguments.
import sys
number=len(sys.argv)
arguments=str(sys.argv)
print ('The Number of arguments:', number, 'arguments.')
print ('Argument List:', arguments)

Output:

C:\Users\Tanushree Thapliyal\Desktop>py yess.py A1 B2 C3 D4
The Number of arguments: 5 arguments.
Argument List: ['yess.py', 'A1', 'B2', 'C3', 'D4']

The 0th index is the script name and is counted in the number of arguments.

Demonstrating the getopt module functions

Let’s go over some of the examples of the getopt module here. We’ll demonstrate some of two of the common functions.

1. Parsing Command Line Options and Parameter List with getopt.getopt()

The getopt() function parses command line options and parameter list. This function accepts three arguments:

  • args is the argument list to be passed.
  • shortopts is the string of options letter that the script wants to recognize.
  • longopts is the list of strings with names of the long options which should be supported.

It returns the list of (option,value) pairs and list of program arguments left after the option list was stripped.

import sys
import getopt

args=sys.argv[1:]
inputfile = ''
outputfile = ''

try:
   opts, args = getopt.getopt(args,"hi:o:",["infile=","outfile="])
except getopt.GetoptError:
   print ('test.py -i <inputfile> -o <outputfile>')
   sys.exit(2)

for opt, arg in opts:
   if opt == '-h':
      print ('args.py -i <inputfile> -o <outputfile>')
      sys.exit()
   elif opt in ("-i", "--infile"):
      inputfile = arg
   elif opt in ("-o", "--outfile"):
      outputfile = arg

print ('Input file is "', inputfile)
print ('Output file is "', outputfile)

Along with accepting the full arguments as --infile and --outfile, we’re also accepting arguments as -i and -o.

NOTE: The above demonstration doesn’t not process the arguments in any way. The purpose of the demonstration is to show the the getopt module parses arguments and makes it easy for us to work with inline arguments.

Here, sys.argv[1:] means that the starting index is 1 because sys.argv[0] is the script name that we do not need to access.

CASE 1: Using single dash(‘ – ‘) and short forms -i and -o.

Output:

py python.py -i=abc.txt -o=xyz.txt
Input file is " abc.txt
Output file is " xyz.txt

CASE 2: Using double dash ( ‘ — ‘) and long forms of the arguments

py python.py --infile=abc.txt --outfile=xyz.txt
Input file is " abc.txt
Output file is " xyz.txt
Longterm

2. GNU Style Parsing With The gnu_getopt() Function

The getopt.gnu_getopt() function is used for GNU style parsing. Its working is similar to the getopt() function except, in this case, the GNU style scanning is used by default which means that option and non-option arguments can be intermixed.

import getopt
import sys

category = '1.0'
fix = False
output_file = 'abc.txt'

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

options, remainder = getopt.gnu_getopt(sys.argv[1:], 'o:f', ['output=','fix', 'category='])

print ('OPTIONS   :', options)

for opt, arg in options:
    if opt in ('-o', '--output'):
        output_filename = arg
    elif opt in ('-f', '--fix'):
        fix = True
    elif opt == '--category':
    	category = arg
        
print ('category   :', category)
print ('fix        :',fix)
print ('output    :', output_file)
print ('remaining :', remainder)

Output:

py yess.py -f not_an_option --output foo

ARGV      : ['-f', 'not_an_option', '--output', 'foo']
OPTIONS   : [('-f', ''), ('--output', 'foo')]
category   : 1.0
fix        : True
output    : abc.txt
remaining : ['not_an_option']

We can also run this code without passing any arguments-

ARGV      : []
OPTIONS   : []
category   : 1.0
fix        : False
output    : abc.txt
remaining : []

If ‘ — ‘ is passed in the argument, getopt stops processing the remaining arguments as options.

py yess.py -f -- --output foo
ARGV      : ['-f', '--', '--output', 'foo']
OPTIONS   : [('-f', '')]
category   : 1.0
fix        : True
output    : abc.txt
remaining : ['--output', 'foo']

Handling exceptions with getopt.GetoptError

When a recognized option is not found in the argument list or when the option that requires an argument is given none, then, an exception error is raised.

Error

Python’s argparse module is an alternative which provides command line interface with less code and more help and informative error messages. You can learn more about handling exceptions.

Conclusion

In this tutorial, we learned about the opt module and its important function and how we can pass command line arguments through this module.

Reference

Official Docs