Using argparse to create useful commandline scripts in Python

From XPUB & Lens-Based wiki
Revision as of 13:32, 26 October 2011 by Michael Murtaugh (talk | contribs)


Commandline (gnu-style) arguments in a nutshell:

  • Positional arguments are simple (unnamed) arguments, appearing without an "option" first
  • Optional arguments are preceded by a "dash" character and name, followed by a value.
  • Finally sometimes an option is simply a "flag", or a name with no value, to typically switches some behaviour on or off (like a True/False value).
  • There are two forms of options, short and long (see below).

Nothing is set in stone, a command can choose to interpret arguments in any way it sees fit. But many programs follow the GNU standard of options for consistency. In Python, using the argparse (formerly optparse) module is an easy way to create commandline programs that are flexible, and behave like other "big" programs. Argparse also automatically produces a "help" screen for explaining (reminding) how a script can be used.

Short and Long options

Example of a short-form option:

ls | head -n1

Example of a long-form option:

ls | head --lines=1

or the equal sign can be (often) omitted

ls | head --lines 1

import argparse

Example program:

import argparse

parser = argparse.ArgumentParser(description="My first Inkscape effect")
parser.add_argument('--id', action="append", help="id(s) of selected elements")
parser.add_argument('path', help="path of svg file to open")

args = parser.parse_args()
print args
  • If the name starts with "--" it's considered an "option", otherwise it's "positional"
  • Action = "append" for a list of values (allows zero or more values to be provided)
  • Default = "foo": To set a default value

Resources