Nov 10, 2018

How to parse Command-Line Arguments in Python

See also:

How to accesse Command-Line Arguments in Python

Python provided a getopt module that helps you parse command-line options and arguments. This module provides two functions and an exception to enable command line argument parsing.

getopt.getopt method:

This method parses command line options and parameter list. Following is simple syntax for this method:
getopt.getopt(args, options[, long_options])
Here is the detail of the parameters:
  • args: This is the argument list to be parsed.
  • options: This is the string of option letters that the script wants to recognize, with options that require an argument should be followed by a colon (:).
  • long_options: This is optional parameter and if specified, must be a list of strings with the names of the long options, which should be supported. Long options, which require an argument should be followed by an equal sign ('='). To accept only long options, options should be an empty string.
This method returns value consisting of two elements: the first is a list of (option, value) pairs. The second is the list of program arguments left after the option list was stripped. Each option-and-value pair returned has the option as its first element, prefixed with a hyphen for short options (e.g., '-h') or two hyphens for long options (e.g., '--help').

exception getopt.GetoptError:

This is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given none.

The argument to the exception is a string indicating the cause of the error. The attributes msg and optgive the error message and related option

usage: -i <inputfile> -o <outputfile>

import sys, getopt

def main(argv):
   inputfile = ''
   outputfile = ''
      opts, args = getopt.getopt(argv,"hi:o:",["inputfile=","outputfile="])
   except getopt.GetoptError:
      print ' -i <inputfile> -o <outputfile>'
   for opt, arg in opts:
      if opt == '-h':
         print ' -i <inputfile> -o <outputfile>'
      elif opt in ("-i", "--inputfile"):
         inputfile = arg
      elif opt in ("-o", "--outputfile"):
         outputfile = arg
   print 'Input file is "', inputfile
   print 'Output file is "', outputfile

if __name__ == "__main__":

$ -h
usage: -i <inputfile> -o <outputfile>

$ -i -o
usage: -i <inputfile> -o <outputfile>

$ -i
Input file is "

Output file is "