{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction to Python 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Command-Line Programs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
\n", "

Learning Objectives

\n", "
\n", "
\n", "\n", "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The IPython Notebook and other interactive tools are great for prototyping code and exploring data, but sooner or later we will want to use our program in a pipeline or run it in a shell script to process thousands of data files. In order to do that, we need to make our programs work like other Unix command-line tools. For example, we may want a program that reads a dataset and prints the average inflammation per patient." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This program does exactly what we want - it prints the average inflammation per patient for a given file." ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ python readings.py --mean data/inflammation-01.csv\n", "5.45\n", "5.425\n", "6.1\n", "...\n", "6.4\n", "7.05\n", "5.9" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We might also want to look at the minimum of the first four lines" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ head -4 inflammation-01.csv | python readings.py --min" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or the maximum inflammations in several files one after another:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ python readings.py --max inflammation-*.csv" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Our scripts should do the following:\n", "\n", "1. If no filename is given on the command line, read data from [standard input](http://swcarpentry.github.io/python-novice-inflammation/reference.html#standard-input).\n", "2. If one or more filenames are given, read data from them and report statistics for each file separately.\n", "3. Use the `--min`, `--mean`, or `--max` flag to determine what statistic to print.\n", "\n", "To make this work, we need to know how to handle command-line arguments in a program, and how to get at standard input. We’ll tackle these questions in turn below." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Command-Line Arguments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using the text editor of your choice, save the following in a text file called `sys-version.py`:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "import sys\n", "print('version is', sys.version)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The first line imports a library called `sys`, which is short for “system”. It defines values such as `sys.version`, which describes which version of Python we are running. We can run this script from the command line like this:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ python sys-version.py" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "version is 3.4.3+ (default, Jul 28 2015, 13:17:50)\n", "[GCC 4.9.3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Create another file called `argv-list.py` and save the following text to it." ] }, { "cell_type": "raw", "metadata": {}, "source": [ "import sys\n", "print('sys.argv is', sys.argv)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The strange name `argv` stands for “argument values”. Whenever Python runs a program, it takes all of the values given on the command line and puts them in the list `sys.argv` so that the program can determine what they were. If we run this program with no arguments:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ python argv-list.py" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "sys.argv is ['argv-list.py']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "the only thing in the list is the full path to our script, which is always `sys.argv[0]`. If we run it with a few arguments, however:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ python argv-list.py first second third" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "sys.argv is ['argv-list.py', 'first', 'second', 'third']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "then Python adds each of those arguments to that magic list.\n", "\n", "With this in hand, let’s build a version of `readings.py` that always prints the per-patient mean of a single data file. The first step is to write a function that outlines our implementation, and a placeholder for the function that does the actual work. By convention this function is usually called `main`, though we can call it whatever we want:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ cat readings-01.py" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import sys\n", "import numpy\n", "\n", "def main():\n", " script = sys.argv[0]\n", " filename = sys.argv[1]\n", " data = numpy.loadtxt(filename, delimiter=',')\n", " for m in data.mean(axis=1):\n", " print(m)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This function gets the name of the script from `sys.argv[0]`, because that’s where it’s always put, and the name of the file to process from `sys.argv[1]`. Here’s a simple test:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ python readings-01.py inflammation-01.csv" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There is no output because we have defined a function, but haven’t actually called it. Let’s add a call to `main`:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ cat readings-02.py" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import sys\n", "import numpy\n", "\n", "def main():\n", " script = sys.argv[0]\n", " filename = sys.argv[1]\n", " data = numpy.loadtxt(filename, delimiter=',')\n", " for m in data.mean(axis=1):\n", " print(m)\n", "\n", "main()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and run that:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ python readings-02.py data/inflammation-01.csv" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "5.45\n", "5.425\n", "6.1\n", "5.9\n", "5.55\n", "6.225\n", "5.975\n", "6.65\n", "6.625\n", "6.525\n", "6.775\n", "5.8\n", "6.225\n", "5.75\n", "5.225\n", "6.3\n", "6.55\n", "5.7\n", "5.85\n", "6.55\n", "5.775\n", "5.825\n", "6.175\n", "6.1\n", "5.8\n", "6.425\n", "6.05\n", "6.025\n", "6.175\n", "6.55\n", "6.175\n", "6.35\n", "6.725\n", "6.125\n", "7.075\n", "5.725\n", "5.925\n", "6.15\n", "6.075\n", "5.75\n", "5.975\n", "5.725\n", "6.3\n", "5.9\n", "6.75\n", "5.925\n", "7.225\n", "6.15\n", "5.95\n", "6.275\n", "5.7\n", "6.1\n", "6.825\n", "5.975\n", "6.725\n", "5.7\n", "6.25\n", "6.4\n", "7.05\n", "5.9" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Handling Multiple Files" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The next step is to teach our program how to handle multiple files. Since 60 lines of output per file is a lot to page through, we’ll start by using three smaller files, each of which has three days of data for two patients:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ ls data/small-*.csv" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "small-01.csv small-02.csv small-03.csv" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ cat data/small-01.csv" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "0,0,1\n", "0,1,2" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ python readings-02.py data/small-01.csv" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "0.333333333333\n", "1.0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using small data files as input also allows us to check our results more easily: here, for example, we can see that our program is calculating the mean correctly for each line, whereas we were really taking it on faith before. This is yet another rule of programming: _test the simple things first_.\n", "\n", "We want our program to process each file separately, so we need a loop that executes once for each filename. If we specify the files on the command line, the filenames will be in `sys.argv`, but we need to be careful: `sys.argv[0]` will always be the name of our script, rather than the name of a file. We also need to handle an unknown number of filenames, since our program could be run for any number of files.\n", "\n", "The solution to both problems is to loop over the contents of `sys.argv[1:]`. The ‘1’ tells Python to start the slice at location 1, so the program’s name isn’t included; since we’ve left off the upper bound, the slice runs to the end of the list, and includes all the filenames. Here’s our changed program `readings-03.py`:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ cat readings-03.py" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "import sys\n", "import numpy\n", "\n", "def main():\n", " script = sys.argv[0]\n", " for filename in sys.argv[1:]:\n", " data = numpy.loadtxt(filename, delimiter=',')\n", " for m in data.mean(axis=1):\n", " print(m)\n", "\n", "main()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and here it is in action:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ python readings-03.py small-01.csv small-02.csv" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "0.333333333333\n", "1.0\n", "13.6666666667\n", "11.0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Handling Command-Line Flags" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The next step is to teach our program to pay attention to the `--min`, `--mean`, and `--max` flags. These always appear before the names of the files, so we could just do this:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ cat readings-04.py" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "import sys\n", "import numpy\n", "\n", "def main():\n", " script = sys.argv[0]\n", " action = sys.argv[1]\n", " filenames = sys.argv[2:]\n", "\n", " for f in filenames:\n", " data = numpy.loadtxt(f, delimiter=',')\n", "\n", " if action == '--min':\n", " values = data.min(axis=1)\n", " elif action == '--mean':\n", " values = data.mean(axis=1)\n", " elif action == '--max':\n", " values = data.max(axis=1)\n", "\n", " for m in values:\n", " print(m)\n", "\n", "main()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This works:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ python readings-04.py --max small-01.csv" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "1.0\n", "2.0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "but there are several things wrong with it:\n", "\n", "1. `main` is too large to read comfortably.\n", "2. If `action` isn’t one of the three recognized flags, the program loads each file but does nothing with it (because none of the branches in the conditional match). [Silent failures](http://swcarpentry.github.io/python-novice-inflammation/reference.html#silence-failure) like this are always hard to debug.\n", "\n", "This version pulls the processing of each file out of the loop into a function of its own. It also checks that `action` is one of the allowed flags before doing any processing, so that the program fails fast:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ cat readings-05.py" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "import sys\n", "import numpy\n", "\n", "def main():\n", " script = sys.argv[0]\n", " action = sys.argv[1]\n", " filenames = sys.argv[2:]\n", " assert action in ['--min', '--mean', '--max'], \\\n", " 'Action is not one of --min, --mean, or --max: ' + action\n", " for f in filenames:\n", " process(f, action)\n", "\n", "def process(filename, action):\n", " data = numpy.loadtxt(filename, delimiter=',')\n", "\n", " if action == '--min':\n", " values = data.min(axis=1)\n", " elif action == '--mean':\n", " values = data.mean(axis=1)\n", " elif action == '--max':\n", " values = data.max(axis=1)\n", "\n", " for m in values:\n", " print(m)\n", "\n", "main()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is four lines longer than its predecessor, but broken into more digestible chunks of 8 and 12 lines.\n", "\n", "Python has a module named [argparse](http://docs.python.org/dev/library/argparse.html) that helps handle complex command-line flags. We will not cover this module in this lesson but you can go to Tshepang Lekhonkhobe’s [Argparse tutorial](http://docs.python.org/dev/howto/argparse.html) that is part of Python’s Official Documentation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Handling Standard Input" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The next thing our program has to do is read data from standard input if no filenames are given so that we can put it in a pipeline, redirect input to it, and so on. Let’s experiment in another script called `count-stdin.py`:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ cat count-stdin.py" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "import sys\n", "\n", "count = 0\n", "for line in sys.stdin:\n", " count += 1\n", "\n", "print(count, 'lines in standard input')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This little program reads lines from a special “file” called `sys.stdin`, which is automatically connected to the program’s standard input. We don’t have to open it — Python and the operating system take care of that when the program starts up — but we can do almost anything with it that we could do to a regular file. Let’s try running it as if it were a regular command-line program:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ python count-stdin.py < small-01.csv" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "2 lines in standard input" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A common mistake is to try to run something that reads from standard input like this:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ count_stdin.py small-01.csv" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "i.e., to forget the `<` character that redirects the file to standard input. In this case, there’s nothing in standard input, so the program waits at the start of the loop for someone to type something on the keyboard. Since there’s no way for us to do this, our program is stuck, and we have to halt it using the `Interrupt` option from the `Kernel` menu in the Notebook.\n", "\n", "We now need to rewrite the program so that it loads data from `sys.stdin` if no filenames are provided. Luckily, `numpy.loadtxt` can handle either a filename or an open file as its first parameter, so we don’t actually need to change `process`. That leaves `main`:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ cat readings-06.py" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "def main():\n", " script = sys.argv[0]\n", " action = sys.argv[1]\n", " filenames = sys.argv[2:]\n", " assert action in ['--min', '--mean', '--max'], \\\n", " 'Action is not one of --min, --mean, or --max: ' + action\n", " if len(filenames) == 0:\n", " process(sys.stdin, action)\n", " else:\n", " for f in filenames:\n", " process(f, action)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let’s try it out:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ python readings-06.py --mean small-01.csv" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "0.333333333333\n", "1.0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That’s better. In fact, that’s done: the program now does everything we set out to do." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
\n", "

Arithmetic on the command line

\n", "
\n", "
\n", "

Write a command-line program that does addition and subtraction:

\n", "\n", "
$ python arith.py add 1 2
\n", "\n", "
3
\n", "\n", "
$ python arith.py subtract 3 4
\n", "\n", "
-1
\n", "\n", "
\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from __future__ import division, print_function\n", "import sys\n", "\n", "def main():\n", " action = sys.argv[1]\n", " number1 = int(sys.argv[2])\n", " number2 = int(sys.argv[3])\n", "\n", " assert action in ['add', 'subtract']\n", "\n", " if action == 'add':\n", " print(number1 + number2)\n", " else:\n", " print(number1 - number2)\n", "\n", "\n", "main()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
\n", "

Finding particular files

\n", "
\n", "
\n", "

Using the glob module introduced earlier, write a simple version of ls that shows files in the current directory with a particular suffix. A call to this script should look like this:

\n", "\n", "
$ python my_ls.py py
\n", "\n", "
left.py\n",
    "right.py\n",
    "zero.py
\n", "\n", "
\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from __future__ import division, print_function\n", "import sys\n", "import glob\n", "\n", "def main():\n", " suffix = sys.argv[1]\n", " files = glob.glob('*.' + suffix)\n", " for file in files:\n", " print(file)\n", "\n", "\n", "main()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
\n", "

Changing flags

\n", "
\n", "
\n", "

Rewrite readings.py so that it uses -n, -m, and -x instead of --min, --mean, and --max respectively. Is the code easier to read? Is the program easier to understand?

\n", "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
\n", "

Adding a help message

\n", "
\n", "
\n", "

Separately, modify readings.py so that if no parameters are given (i.e., no action is specified and no filenames are given), it prints a message explaining how it should be used.

\n", "
\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from __future__ import division, print_function\n", "import sys\n", "\n", "def main():\n", " if len(sys.argv) < 2:\n", " print(\"\"\"This program should be called with an action and a filename or list of filenames, like so:\n", " $ python readings.py [action] [filename(s)]\n", " In the above, action is either '--min', '--mean', or '--max'.\n", " filename(s) is a filename or several filenames, or a file in standard input.\"\"\")\n", " script = sys.argv[0]\n", " action = sys.argv[1]\n", " filenames = sys.argv[2:]\n", " assert action in ['--min', '--mean', '--max'], \\\n", " 'Action is not one of --min, --mean, or --max: ' + action\n", " if len(filenames) == 0:\n", " process(sys.stdin, action)\n", " else:\n", " for f in filenames:\n", " process(f, action)\n", "\n", "\n", "def process(filename, action):\n", " data = numpy.loadtxt(filename, delimiter=',')\n", "\n", " if action == '--min':\n", " values = data.min(axis=1)\n", " elif action == '--mean':\n", " values = data.mean(axis=1)\n", " elif action == '--max':\n", " values = data.max(axis=1)\n", "\n", " for m in values:\n", " print(m)\n", "\n", "\n", "main()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
\n", "

Adding a default action

\n", "
\n", "
\n", "

Separately, modify readings.py so that if no action is given it displays the means of the data.

\n", "
\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def main():\n", " script = sys.argv[0]\n", " if len(sys.argv) > 1:\n", " action = sys.argv[1]\n", " else:\n", " action = '--mean'\n", " filenames = sys.argv[2:]\n", " assert action in ['--min', '--mean', '--max'], \\\n", " 'Action is not one of --min, --mean, or --max: ' + action\n", " if len(filenames) == 0:\n", " process(sys.stdin, action)\n", " else:\n", " for f in filenames:\n", " process(f, action)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
\n", "

A file-checker

\n", "
\n", "
\n", "

Write a program called check.py that takes the names of one or more inflammation data files as arguments and checks that all the files have the same number of rows and columns. What is the best way to test your program?

\n", "
\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from __future__ import division, print_function\n", "import sys\n", "import numpy as np\n", "\n", "def main():\n", " script = sys.argv[0]\n", " filenames = sys.argv[1:]\n", " print filenames[0]\n", " shape0 = np.loadtxt(filenames[0]).shape\n", " for file in filenames[1:]:\n", " assert np.loadtxt(file).shape == shape0, 'Shape of {} does not match'.format(file)\n", "\n", "\n", "main()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from __future__ import division, print_function\n", "import sys\n", "import numpy as np\n", "\n", "def main():\n", " script = sys.argv[0]\n", " filenames = sys.argv[1:]\n", " shape0 = np.loadtxt(filenames[0], delimiter=',').shape\n", " for file in filenames[1:]:\n", " assert np.loadtxt(file, delimiter=',').shape == shape0, 'Shape of {} does not match'.format(file)\n", "\n", "\n", "main()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
\n", "

Counting lines

\n", "
\n", "
\n", "

Write a program called line-count.py that works like the Unix wc command:

\n", "\n", "
\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import sys\n", "\n", "def main():\n", " if len(sys.argv) < 2:\n", " count = 0\n", " for line in sys.stdin:\n", " count += 1\n", "\n", " print(count, 'lines in standard input')\n", " else:\n", " total_lines = 0\n", " filenames = sys.argv[1:]\n", " for file in filenames:\n", " file_contents = np.loadtxt(file)\n", " print('Lines in', file, ':', len(file_contents))\n", " total_lines += 1\n", " print('Total number of lines:', total_lines)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.11" } }, "nbformat": 4, "nbformat_minor": 0 }