{ "metadata": { "name": "", "signature": "sha256:a4547d44e81ec5504c2ed880553ed5517e1eea30973fbb52fc972c141f9386e3" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# CR\u00dcCIAL P\u0178THON Week 9: argparse" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from IPython.core.display import Image \n", "Image(url='http://labrosa.ee.columbia.edu/crucialpython/logo.png', width=600) " ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## When IPython notebooks grow up...\n", "\n", "Notebooks are great, but sometimes you need a program that runs from the command-line. Sometimes, your program even has options! Flags! Variable-length argument lists!\n", "\n", "What ever shall we do?\n", "\n", "## ArgParse\n", "If this was C, we'd most likely use [`getopt(3)`](http://man7.org/linux/man-pages/man3/getopt.3.html) to set up an argument parser. This provides the familiar style of `-v` and `--verbose` command-line arguments that we all know and love.\n", "\n", "The Python analog of `getopt` is [ArgParse](https://docs.python.org/2.7/library/argparse.html): a module that takes the pain out of constructing argument parsers. Today, we'll look through some of its basic functionality." ] }, { "cell_type": "code", "collapsed": false, "input": [ "# First, we import the argparse module\n", "import argparse" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# Let's define a silly function to add and multiply numbers\n", "def my_function(lower_bound, upper_bound, multiply=None, verbose=False):\n", " \n", " value = 0\n", " for x in range(lower_bound, upper_bound):\n", " if verbose:\n", " print 'value <- %3d + %3d' % (value, x)\n", " value = value + x\n", " \n", " \n", " if multiply:\n", " for x in multiply:\n", " if verbose:\n", " print 'value <- %3d * %3d' % (value, x)\n", " value = value * x\n", " \n", " return value" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# Let's define a function to process a list of string arguments\n", "def process_arguments(args):\n", "\n", " # First, construct the parser\n", " parser = argparse.ArgumentParser(description=\"Adds a set of numbers, and then multiplies by an optional list\")\n", " \n", " # Let's add our first argument\n", " parser.add_argument('-l', # Short switch\n", " '--lower-bound', # Long switch\n", " dest='lower_bound', # Destination in our option dict\n", " type=int, # Type of argument we expect\n", " default=0, # Default value\n", " help='Lower bound for the summation' # Descriptive text\n", " )\n", " \n", " # And another\n", " parser.add_argument('-u',\n", " '--upper-bound',\n", " dest='upper_bound',\n", " type=int,\n", " default=10,\n", " help='Upper bound for the summation')\n", " \n", " # How about optional positional arguments?\n", " parser.add_argument(dest='multiply',\n", " nargs='*',\n", " type=float,\n", " default=None,\n", " help='One or numbers to multiply with the sum')\n", " \n", " # A binary switch?\n", " parser.add_argument('-v',\n", " '--verbose',\n", " dest='verbose',\n", " action='store_true',\n", " default=False,\n", " help='verbose output')\n", " \n", " # Finally, apply the parser to the argument list\n", " options = parser.parse_args(args)\n", " \n", " # And return it as a dict\n", " return vars(options)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# A first test, use the help function:\n", "print process_arguments(['-h'])" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# If we call with no arguments\n", "print process_arguments([])" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# Or lots of arguments\n", "print process_arguments(['-l', '3', '--upper-bound', '8', '--verbose', '-1', '2', '7'])" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# To actually use this on the command line, get sys.argv[1:]\n", "import sys\n", "options = process_arguments(sys.argv[1:])" ], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }