Skip navigation
NASA Logo, National Aeronautics and Space Administration
Modeling Guru Banner
Currently Being Moderated

The optparse and argpase Python Modules

VERSION 1 
Created on: Dec 17, 2015 8:03 AM by Jules Kouatchou - Last Modified:  Dec 17, 2015 8:36 AM by Jules Kouatchou

Reference Documents

 

  1. Python’s optparse for human beings
  2. optparse – Command line option parser to replace getopt
  3. argparse – Command line option and argument parsing
  4. Argparse Tutorial

 

Introduction

  • Python modules that allow your program to easily parse command line options it receives.
  • Take care of some of the very common tasks, such as handling -h command line option.
  • argparse is based on optparse (no longer supported), and therefore very similar in terms of usage.
  • In many cases argparse can be used as a straightforward replacement by updating the names of the classes and methods used.

 

Comments on argparse

With respect to optparse, argparse is better for:

  • Handling positional arguments
  • Supporting sub-commands
  • Allowing alternative option prefixes like + and /
  • Handling zero-or-more and one-or-more style arguments
  • Producing more informative usage messages
  • Providing a much simpler interface for custom types and actions

 

What We Want to Accomplish

  • Support for a standalone command line options (boolean options).
  • Support for mandatory (required) options.
  • Support for options with one or more arguments.
  • Set default values for options.
  • Handle dependency between options.
  • Grouping of options in help screen.
  • Customizing help screen.

 

Simple Test Case

Assume that you have a Python script (myScript.py) that is run using the command line:

 

myScript.py -x execFile -i inputFile -o outputFile -p param otherArgs

 

 

We want:

  • To parse the command line options
  • To add a help option
  • To print the usage of the Python script
  • The user to provide at least execFile and inputFile
  • Default values be set for outputFile and param
  • otherArgs to be optional

 

Initial Step:

 

With optparse

import optparse
oparser = optparse.OptionParser()

 

You may want to add more option when you instantiate the OptionParser class:

 

oparser = optparse.OptionParser(version='%prog version 0.0',
                               description='How to use the script %prog with optparse')

 

With argparse

import argparse
aparser = argparse.ArgumentParser(version='%(prog)s version 0.0',
                               description='How to use the script %prog with argparse')

 

Adding Options

 

With optparse

oparser.add_option('-x', '--exec', help='Execution file',
                  dest='myExecFile', action='store', 
                  metavar='executionFile')
 
oparser.add_option('-i', '--input', help='Input file',
                  dest='myInputFile', action='store', 
                  metavar='inputFile')
 
oparser.add_option('-o', '--output', help='Output file',
                  dest='myOutputFile', action='store', default='output.txt',
                  metavar='outputFile')
 
oparser.add_option('-p', '--param', help='Input parameter',
                  dest='myParameter', action='store', type='float', 
                  default=1.0, metavar='inputParameter')

 

With argparse

aparser.add_argument('-x', '--exec', help='Execution file',
                  dest='myExecFile', action='store', metavar='executionFile')

aparser.add_argument('-i', '--input', help='Input file',
                  dest='myInputFile', action='store',
                  type=argparse.FileType('rt'), metavar='inputFile')

aparser.add_argument('-o', '--output', help='Output file',
                  dest='myOutputFile', action='store', default='ouput.txt',
                  type=argparse.FileType('wt'), metavar='outputFile')

aparser.add_argument('-p', '--param', help='Input parameter',
                  dest='myParameter', action='store', type=float,
                  default=1.0, metavar='inputParameter')

aparser.add_argument('--optional', nargs='*', help='Optional arguments')

 

Parse the Command Line

 

(oopts, oargs) = oparser.parse_args()

 

aargs = aparser.parse_args()

 

Making Sure Arguments Are Provided

 

if oopts.myExecFile is None:
   print "You need to provide the execution file"
   oparser.print_help()
   sys.exit(0)
 
if oopts.myInputFile is None:
   print "You need to provide an input file"
   oparser.print_help()
   sys.exit(1)

 

Running a Test Case

 

With optparse

Consider the Python script (o_myScript.py):

#!/usr/bin/env python
 
# Load the modules
#-----------------
import sys
import optparse
 
# Instantiate the OptionParser class
#-----------------------------------
oparser = optparse.OptionParser(version='%prog version 0.0',
                               description='How to use the script')
 
# Add the options
#----------------
oparser.add_option('-x', '--exec', help='Execution file',
                  dest='myExecFile', action='store', metavar='executionFile')
 
oparser.add_option('-i', '--input', help='Input file',
                  dest='myInputFile', action='store', metavar='inputFile')
 
oparser.add_option('-o', '--output', help='Output file',
                  dest='myOutputFile', action='store', default='ouput.txt',
                  metavar='outputFile')
 
oparser.add_option('-p', '--param', help='Input parameter',
                  dest='myParameter', action='store', type='float',
                  default=1.0, metavar='inputParameter')
 
# Parse the command line
#-----------------------
(opts, args) = oparser.parse_args()
 
ne = 0
 
# Make sure arguments are provided
#---------------------------------
if opts.myExecFile is None:
   print "You need to provide the execution file"
   oparser.print_help()
   ne += 1
   sys.exit(ne)
 
if opts.myInputFile is None:
   print "You need to provide an input file"
   oparser.print_help()
   ne += 1
   sys.exit(ne)
 
# Print all the options
#----------------------
print 'Execution file      :', opts.myExecFile
print 'Input file             :', opts.myInputFile
print 'Output file          :', opts.myOutputFile
print 'Input parameter  :', opts.myParameter
print 'Other arguments :', args

 

You can execute it using the sample command lines:

 

python o_myScript.py -x prog.x -i myFile.in
python o_myScript.py -p 3.6 -x prog.x -i myFile.in 32 simpleTest
python o_myScript.py -x prog.x

 

 

With argparse

Consider the Python script (a_myScript.py):

 

#!/usr/bin/env python
 
# Load the modules
#-----------------
import sys
import argparse
 
# Instantiate the OptionParser class
#-----------------------------------
aparser = argparse.ArgumentParser(version='%(prog)s version 0.0',
                               description='How to use the script')
 
# Add the options
#----------------
aparser.add_argument('-x', '--exec', help='Execution file',
                  dest='myExecFile', action='store', metavar='executionFile')
 
aparser.add_argument('-i', '--input', help='Input file',
                  dest='myInputFile', action='store',
                  type=argparse.FileType('rt'), metavar='inputFile')
 
aparser.add_argument('-o', '--output', help='Output file',
                  dest='myOutputFile', action='store', default='ouput.txt',
                  type=argparse.FileType('wt'), metavar='outputFile')
 
aparser.add_argument('-p', '--param', help='Input parameter',
                  dest='myParameter', action='store', type=float,
                  default=1.0, metavar='inputParameter')
 
aparser.add_argument('--optional', nargs='*', help='Optional arguments')
 
# Parse the command line
#-----------------------
aargs = aparser.parse_args()
 
ne = 0
 
# Make sure arguments are provided
#---------------------------------
if aargs.myExecFile is None:
   print "You need to provide the execution file"
   aparser.print_help()
   ne += 1
   sys.exit(ne)
 
if aargs.myInputFile is None:
   print "You need to provide an input file"
   aparser.print_help()
   ne += 1
   sys.exit(ne)
 
# Print all the options
#----------------------
print 'Execution file      :', aargs.myExecFile
print 'Input file             :', aargs.myInputFile
print 'Output file          :', aargs.myOutputFile
print 'Input parameter  :', aargs.myParameter
print 'Other arguments :', aargs.optional

 

You can execute it using the sample command lines:

python a_myScript.py -x prog.x -i myFile.in
python a_myScript.py -p 3.6 -x prog.x -i myFile.in --optional 32 simpleTest
python a_myScript.py -x prog.x
Comments (0)
USAGov logo NASA Logo - nasa.gov