• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

How to parse command line arguments in Python

Contents

  • Argparse
    • Installation
    • Usage
    • Example 1: Fibonacci
    • Example 2: less
    • Example 3: copy-paste template
  • Optparse
  • See also

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.

Installation

I had to install python-argparse on my old Ubuntu machine before I could use it.

Usage

As far as I've just tried it, you can use argparse very similar to optparse. See this diff for my switch from optparse to argparse for a simple script.

It is very easy to add command line options argument (if you require an option, it would not be an option any more, would it? I'll try to call them arguments from now on):

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from argparse import ArgumentParser

parser = ArgumentParser()

# Add more options if you like
parser.add_argument(
    "-f",
    "--file",
    dest="myFilenameVariable",
    help="write report to FILE",
    metavar="FILE",
)
parser.add_argument(
    "-q",
    "--quiet",
    action="store_false",
    dest="verbose",
    default=True,
    help="don't print status messages to stdout",
)

args = parser.parse_args()

print(args.myFilenameVariable)

Every option has some values like:

  • dest: You will access the value of option with this variable
  • help: This text gets displayed whey someone uses --help.
  • default: If the command line argument was not specified, it will get this default value.
  • action: Actions tell optparse what to do when it encounters an option on the command line. action defaults to store. These actions are available:
    • store: take the next argument (or the remainder of the current argument), ensure that it is of the correct type, and store it to your chosen destination dest.
    • store_true: store True in dest if this flag was set.
    • store_false: store False in dest if this flag was set.
    • store_const: store a constant value
    • append: append this option’s argument to a list
    • count: increment a counter by one
    • callback: call a specified function
  • nargs: ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The nargs keyword argument associates a different number of command-line arguments with a single action.
  • required: Mark a command line argument as non-optional (required).
  • choices: Some command-line arguments should be selected from a restricted set of values. These can be handled by passing a container object as the choices keyword argument to add_argument(). When the command line is parsed, argument values will be checked, and an error message will be displayed if the argument was not one of the acceptable values.
  • type: Use this command, if the argument is of another type (e.g. int or float).

argparse automatically generates a help text. So if you call python myScript.py --help you will get something like that:

usage: ikjMultiplication.py [-h] [-i FILE]

ikjMatrix multiplication

optional arguments:
  -h, --help  show this help message and exit
  -i FILE     input file with two matrices

Example 1: Fibonacci

It is absolutely no problem to calculate the 100,000st Fibonacci number.

#!/usr/bin/env python
# -*- coding: utf-8 -*-


def mul(A, B):
    a, b, c = A
    d, e, f = B
    return a * d + b * e, a * e + b * f, b * e + c * f


def pow(A, n):
    if n == 1:
        return A
    if n & 1 == 0:
        return pow(mul(A, A), n // 2)
    else:
        return mul(A, pow(mul(A, A), (n - 1) // 2))


def fib(n):
    if n < 2:
        return n
    return pow((1, 1, 0), n - 1)[0]


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Fibonacci-Script")
    parser.add_argument(
        "-n", metavar="N", type=int, help="print the N-th fibonacci number"
    )

    args = parser.parse_args()
    print(fib(args.n))

Note that it uses type=int not type="int" as it was in optparse.

Example 2: less

#!/usr/bin/env python
# -*- coding: utf-8 -*-


def mul(A, B):
    a, b, c = A
    d, e, f = B
    return a * d + b * e, a * e + b * f, b * e + c * f


def pow(A, n):
    if n == 1:
        return A
    if n & 1 == 0:
        return pow(mul(A, A), n // 2)
    else:
        return mul(A, pow(mul(A, A), (n - 1) // 2))


def fib(n):
    if n < 2:
        return n
    return pow((1, 1, 0), n - 1)[0]


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="less script")
    parser.add_argument(
        "-f", "--file", dest="filename", help="write report to FILE", metavar="FILE"
    )
    parser.add_argument(
        "-n", dest="n", default=10, type=int, help="how many lines get printed"
    )
    parser.add_argument(
        "-q",
        "--quiet",
        action="store_false",
        dest="verbose",
        default=True,
        help="don't print status messages to stdout",
    )

    args = parser.parse_args()
    if args.verbose:
        print("Will open file now and print %i lines." % args.n)

    f = open(args.filename, "r")
    for i in range(args.n):
        print(f.readline())

Example 3: copy-paste template

This is how I use it most of the time. I want to show defaults in help:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Example for a simple program with a command line parser."""

import os


def is_valid_file(parser, arg):
    """
    Check if arg is a valid file that already exists on the file system.

    Parameters
    ----------
    parser : argparse object
    arg : str

    Returns
    -------
    arg
    """
    arg = os.path.abspath(arg)
    if not os.path.exists(arg):
        parser.error("The file %s does not exist!" % arg)
    else:
        return arg


def get_parser():
    """Get parser object for script xy.py."""
    from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter

    parser = ArgumentParser(
        description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter
    )
    parser.add_argument(
        "-f",
        "--file",
        dest="filename",
        type=lambda x: is_valid_file(parser, x),
        help="write report to FILE",
        metavar="FILE",
    )
    parser.add_argument(
        "-n", dest="n", default=10, type=int, help="how many lines get printed"
    )
    parser.add_argument(
        "-q",
        "--quiet",
        action="store_false",
        dest="verbose",
        default=True,
        help="don't print status messages to stdout",
    )
    return parser


if __name__ == "__main__":
    args = get_parser().parse_args()

Optparse

Deprecated since version 2.7: The optparse module is deprecated and will not be developed further; development will continue with the argparse module.

Parsing command line arguments with optparse was very easy, but as it is deprecated and argparse works almost the same way, I will not make any examples. Just use argparse.

See also

  • Why use argparse rather than optparse?
  • Python argparse and bash completion

Published

Jul 18, 2012
by Martin Thoma

Category

Code

Tags

  • command line arguments 1
  • Python 141

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor