Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to use argparse

📅 2013-Feb-20 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ argparse, python ⬩ 📚 Archive

The argparse module makes it really easy to read, parse and use the input arguments passed to a Python program.

Usage is in 3 simple steps:

Here is a simple program that illustrates usage of argparse with different types of input arguments:

import argparse
import sys

def foo(args):
    print args

    print "Radius:   ", args.rad
    print "Distance: ", args.d
    print "Name:     ", args.name
    print "Recompute:", args.recompute
    print "In files: ", args.in_files

def main():

    # Create parser
    arg_parser = argparse.ArgumentParser(description="This program achieves nothing!")

    # Add arguments you want to handle
    modes = ["release", "debug"]
    arg_parser.add_argument("--radius",    type=float,          default=1.2,   help="Radius of the component")
    arg_parser.add_argument("-d",          type=int,            default=9,     help="Distance to the component")
    arg_parser.add_argument("--name",      type=str,                           help="Name of component")
    arg_parser.add_argument("--mode",      type=str,            choices=modes, help="Mode to use. Should be either release or debug")
    arg_parser.add_argument("--recompute", action="store_true", default=False, help="Indicate if recomputation is needed")
    arg_parser.add_argument("--in_files",  type=str,            nargs="+",     help="One or more input file paths")

    if len(sys.argv) == 1:
        arg_parser.print_help()
        sys.exit(1)

    # Parse sys.argv using parser
    args = arg_parser.parse_args()

    # Pass arguments around
    foo(args)

if __name__ == "__main__":
    main()

ArgumentParser

This call has many useful options, the only one I actually use is:

add_argument

This call has many useful options. Many of them are needed in most scripts:

Tried with: Python 3.5 and Ubuntu 16.04