Python argparse

Command-line processing

As of Python 2.7, the preferred command-line parsing library is argparse. The pattern is straightforward – create an ArgumentParser, add all the command-line options, then call it and extract arguments.

import argparse
def commandline():
  parser = argparse.ArgumentParser(
    description='Your command-line description',
    fromfile_prefix_chars='@')

  parser.add_argument('path', nargs='*', help='help string')
  parser.add_argument('--user', action='append', help='help string')
  parser.add_argument('--verbose', action='count', default=0, help='help string')
  parser.add_argument('--quiet', action='store_true', help='help string')

  args = parser.parser_args()

  print '  path   =    %s' % ',\n              '.join(args.path)
  print '  user   =    %s' % ',\n              '.join(args.user)
  print '  verbose= %d' % args.verbose
  print '  quiet = %s' % 'True' if args.quiet else 'False'

Given

sub/one sub/three --user=sub/two --verbose --quiet --verbose

this produces

path    = sub/one
          sub/three
user    = sub/two
verbose = 2
quiet   = True

Arguments are positional or optional. In the example above, all arguments not attached to one of the listed options is gathered up into the ‘path’ positional argument.

More reading

Reference: http://docs.python.org/2.7/library/argparse.html

Tutorial: http://docs.python.org/2.7/howto/argparse.html

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>