Python-Parsing arguments through Argparse


The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv[1].

Argparse module automatically generates help and usage messages, making it easier to run. The module is highly user configurable. For example, user can define arguments that are mandatory, optional, or even specify default values for the arguments. Some of the features of argparse module can be illustrated from the following example:

import argparse;
import sys

argv = sys.argv[1:]

command_choices = ["create", "mount", "unmount", "delete"];

#Description of the module
parser = argparse.ArgumentParser(description="Argument parser Example")

"""
The following argument can take one of four choices,
create, mount, unmount and delete. It throws an error
if any other choice is given
"""

parser.add_argument("command",
                    choices=command_choices,
                    help="The commands are create, mount, unmount, delete")

"""
Its mandatory for the user to give the required_arg as
an argument in the command line, otherwise it throws an
error. required = True is added for this purpose
"""

parser.add_argument("--required_arg",
                    required=True,
                    help="The argument which is mandatory")

"""
The following argument is optional as 
required option is not given
"""
parser.add_argument("--optional_arg",
                    help="The argument which is optional")

"""
The argument is optional. If no value is given, the 
argument is given the default value. 
"""
parser.add_argument("--size_mb",
                    default="100",
                    help="The size in MB")

parser.add_argument("--encryption_alg",
                    default="aes",
                    help="The encryption algorithm supports aes")

args = parser.parse_args(argv)

"""
Print the values of the required arguments
"""

print "required_arg is : ", args.required_arg
print "optional_arg is : ", args.optional_arg
print "size_mb is      : ", args.size_mb
print "Command is      : ", args.command
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s