Fork this blog on GitHub Fork this blog on GitHub

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'
  exit()


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

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 argparse module:


import argparse

parser = argparse.ArgumentParser(description='This script does something useful with an argument.')
parser.add_argument('useful_arg', metavar='USEFUL_ARGUMENT', help='a useful argument')
args = parser.parse_args()
useful_arg = args.useful_arg

 

Next entry

Previous entry

Similar entries

Comments

  1. thens

    thens on 02/06/2013 2:07 p.m.

    I'm used to use argparse nowadays as well, but isn't there a "newer/better" solution released (agaaain)?

Post your comment

Pingbacks

Pingbacks are closed.