p

python tutorial - Python Argparse - learn python - python programming



What is 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.
  • The Argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments." - from Argparse - Parser for command-line options, arguments and sub-commands

The following description is from The Argparse module is now part of the Python standard library!

  • The Argparse module provides an easy, declarative interface for creating command line tools, which knows how to:
    • parse the arguments and flags from sys.argv
    • convert arg strings into objects for your program
    • format and print informative help messages
  • The Argparse module improves on the standard library optparse module in a number of ways including:
    • handling positional arguments
    • supporting sub-commands
    • allowing alternative option prefixes like + and /
    • handling zero-or-more and one-or-more style arguments
    • producing more informative usage messages
    • providing a much simpler interface for custom types and actions

A simple sample

Let's look at our first sample of using Argparse:

# arg.py

import Argparse
import sys

def check_arg(args=None):
    parser = argparse.ArgumentParser(description='Script to learn basic Argparse')
    parser.add_argument('-H', '--host',
                        help='host ip',
                        required='True',
                        default='localhost')
    parser.add_argument('-p', '--port',
                        help='port of the web server',
                        default='8080')
    parser.add_argument('-u', '--user',
                        help='user name',
                        default='root')

    results = parser.parse_args(args)
    return (results.host,
            results.port,
            results.user)

if __name__ == '__main__':
    h, p, u = check_arg(sys.argv[1:])
    print 'h =',h
    print 'p =',p
    print 'u =',u
click below button to copy the code. By Python tutorial team

If we run it:

$ python arg.py -H 192.17.23.5
h = 192.17.23.5
p = 8080
u = root

Note that the 'host' arg is set as 'required'. So, if we run the code without feeding host ip, we'll get an error like this:

$ python arg.py
usage: arg.py [-h] -H HOST [-p PORT] [-u USER]
arg.py: error: argument -H/--host is required
click below button to copy the code. By Python tutorial team

Help option

Also, we need to look at how the help works:

$ python arg.py -h
usage: arg.py [-h] -H HOST [-p PORT] [-u USER]

Script to learn basic Argparse

optional arguments:
  -h, --help            show this help message and exit
  -H HOST, --host HOST  host ip
  -p PORT, --port PORT  port of the web server
  -u USER, --user USER  user name
click below button to copy the code. By Python tutorial team

Notice that we used -H for host-ip mandatory option instead of lower case 'h' because it is reserved for 'help.

Integer input

Another sample code:

# arg.py

import Argparse
import sys

def int_args(args=None):
    parser = argparse.ArgumentParser(description='Processing integers.')
    parser.add_argument('integers',
                        metavar='N',
                        type=int,
                        nargs='+',
                        help='integer args')
    return parser.parse_args()

if __name__ == '__main__':
    print int_args(sys.argv[1:])
click below button to copy the code. By Python tutorial team

Just to see how it works, let's request 'help':

$ python arg.py -h
usage: arg.py [-h] N [N ...]

Processing integers.

positional arguments:
  N           integer args

optional arguments:
  -h, --help  show this help message and exit
click below button to copy the code. By Python tutorial team

We need to check the add_argument() method in ArgumentParser.add_argument():

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
click below button to copy the code. By Python tutorial team

1.name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.
2.action - The basic type of action to be taken when this argument is encountered at the command line.
3.nargs - The number of command-line arguments that should be consumed.
4.const - A constant value required by some action and nargs selections.
5.default - The value produced if the argument is absent from the command line.
6.type - The type to which the command-line argument should be converted.
7.choices - A container of the allowable values for the argument.
8.required - Whether or not the command-line option may be omitted (optionals only).
9.help - A brief description of what the argument does.
10.metavar - A name for the argument in usage messages.
11.dest - The name of the attribute to be added to the object returned by parse_args().

  • Now, it's time to run the code:
$ arg.py 1 2 3 4 5
Namespace(integers=[1, 2, 3, 4, 5])
click below button to copy the code. By Python tutorial team
  • The '+' in nargs='+', just like '*', makes all command-line args present to be gathered into a list.
  • If we provide a wrong type arg such as a float type, we'll get an error:
$ arg.py 1.9999 2 3 4 5
usage: arg.py [-h] N [N ...]
arg.py: error: argument N: invalid int value: '1.9999'
click below button to copy the code. By Python tutorial team

Related Searches to Argparse