Fork this blog on GitHub Fork this blog on GitHub

Archives July 2, 2012

Python Argparse - Parsing Command Line Scipt Arguments

The python argparse module is quite nifty.  In the past I have used code like this to parse arguments to command line scripts:

import sys

prog_name        = sys.argv[0]

def printUsage():
  print 'Usage: ' + prog_name + ' USEFUL_ARGUMENT'
  print 'This script does something useful with an argument.\n'
  print 'Examples:'
  print '  '+ prog_name + ' USEFUL_ARGUMENT\n'

if '-h' in sys.argv or '--help' in sys.argv or len(sys.argv) != 1:

useful_arg = sys.argv[0]

The argparse module helps to eliminate boilerplate code, provides nice formatting for free, and provides useful features. Here is the same code using the ...

Continue reading