FANDOM


There are multiple ways to create Command Line Interfaces with Python. But on this page we are going to be looking at using Argparse, the default Python program for creating command line programs.


Creating a parserEdit

The first step in using the argparse module (aside from importing it) is creating an ArgumentParser object:

parser = argparse.ArgumentParser(description='Process some integers.')

The ArgumentParser object will hold all the information necessary to parse the command line into Python data types.

Adding argumentsEdit

Filling an ArgumentParser with information about program arguments is done by making calls to the add_argument() method. Generally, these calls tell the ArgumentParser how to take the strings on the command line and turn them into objects. This information is stored and used when parse_args() is called.

For example:

parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max,
                    help='sum the integers (default: find the max)')

Later, calling parse_args() will return an object with two attributes, integers and accumulate. The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.


Optional argumentsEdit

Optional arguments are proceeded with a dash symbol. The -h or --help flag is a good example of an optional argument.  An example of building an optional argument for yourself would be something like:

parser = argparse.ArgumentParser()

parser.add_argument("-n", "--new", help="Create new list", action="store_true")

the action "store_true" is used for storing the value "True", so we can later check if the optional argument has been flagged by the user :

# Checking arguments.
if args.new:
    # Run function.
    create_new_list()


GroupsEdit

group  lets you  make sure that only one of the arguments in the mutually exclusive group is present on the command line at once.

For example:

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()

group.add_argument("-n", "--new", help="Create new list", action="store_true")

Other types of groups can be made but this mutually exclusive group is particularly useful.

Parsing argumentsEdit

ArgumentParser parses arguments through the parse_args() method. This will inspect the command line, convert each argument to the appropriate type and the invoke the appropriate action. In most cases, this means a simple Namespace object will be built up from attributes parsed out of the command line:

>>> parser.parse_args(['--sum', '7', '-1', '42'])
Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])

In a script, parse_args() will typically be called with no arguments, and the ArgumentParser will automatically determine the command-line arguments from sys.srgv.


ReferencesEdit

argparse - Parser for command-line options, arguments and sub-commands

Python Advanced Tutorial 3 - Argparse

Building Beautiful Command Line Interfaces with Python

Python Argparse Cookbook

Community content is available under CC-BY-SA unless otherwise noted.