Command-Line Programs

Overview

How can I write Python programs that will work like Unix command-line tools?

Objectives

Use the values of command-line arguments in a program.

Handle flags and files separately in a command-line program.

Read data from standard input in a program so that it can be used in a pipeline.

The Jupyter 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.

Switching to Shell Commands

In this lesson we are switching from typing commands in a Python interpreter to typing
commands in a shell terminal window (such as bash). When you see a $ in front of a
command that tells you to run that command in the shell rather than the Python interpreter.

This program does exactly what we want - it prints the average inflammation per patient
for a given file.

$ python ../code/readings_04.py --mean inflammation-01.csv

5.45
5.425
6.1
...
6.4
7.05
5.9

We might also want to look at the minimum of the first four lines

$ head -4 inflammation-01.csv | python ../code/readings_06.py --min

or the maximum inflammations in several files one after another:

$ python ../code/readings_04.py --max inflammation-*.csv

Our scripts should do the following:

If no filename is given on the command line, read data from
standard input.

If one or more filenames are given, read data from them and report statistics for each file
separately.

Use the --min, --mean, or --max flag to determine what statistic to print.

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.

Command-Line Arguments

Using the text editor of your choice,
save the following in a text file called sys_version.py:

importsysprint('version is',sys.version)

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:

$ python sys_version.py

version is 3.4.3+ (default, Jul 28 2015, 13:17:50)
[GCC 4.9.3]

Create another file called argv_list.py and save the following text to it.

importsysprint('sys.argv is',sys.argv)

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:

$ python argv_list.py

sys.argv is ['argv_list.py']

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:

$ python argv_list.py first second third

sys.argv is ['argv_list.py', 'first', 'second', 'third']

then Python adds each of those arguments to that magic list.

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:

Running Versus Importing

Running a Python script in bash is very similar to
importing that file in Python.
The biggest difference is that we don’t expect anything
to happen when we import a file,
whereas when running a script, we expect to see some
output printed to the console.

In order for a Python script to work as expected
when imported or when run as a script,
we typically put the part of the script
that produces output in the following if statement:

if__name__=='__main__':main()# Or whatever function produces output

When you import a Python file, __name__ is the name
of that file (e.g., when importing readings.py,
__name__ is 'readings'). However, when running a
script in bash, __name__ is always set to '__main__'
in that script so that you can determine if the file
is being imported or run as a script.

The Right Way to Do It

If our programs can take complex parameters or multiple filenames,
we shouldn’t handle sys.argv directly.
Instead,
we should use Python’s argparse library,
which handles common cases in a systematic way,
and also makes it easy for us to provide sensible error messages for our users.
We will not cover this module in this lesson
but you can go to Tshepang Lekhonkhobe’s
Argparse tutorial
that is part of Python’s Official Documentation.

Handling Multiple Files

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:

$ ls small-*.csv

small-01.csv small-02.csv small-03.csv

$ cat small-01.csv

0,0,1
0,1,2

$ python ../code/readings_02.py small-01.csv

0.333333333333
1.0

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.

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.

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:

The Right Way to Do It

At this point,
we have created three versions of our script called readings_01.py,
readings_02.py, and readings_03.py.
We wouldn’t do this in real life:
instead,
we would have one file called readings.py that we committed to version control
every time we got an enhancement working.
For teaching,
though,
we need all the successive versions side by side.

Handling Command-Line Flags

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:

If we do not specify at least two additional arguments on the
command-line, one for the flag and one for the filename, but only
one, the program will not throw an exception but will run. It assumes that the file
list is empty, as sys.argv[1] will be considered the action, even if it
is a filename. Silent failures like this
are always hard to debug.

The program should check if the submitted action is one of the three recognized flags.

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:

$ cat ../code/readings_05.py

importsysimportnumpydefmain():script=sys.argv[0]action=sys.argv[1]filenames=sys.argv[2:]assertactionin['--min','--mean','--max'], \
'Action is not one of --min, --mean, or --max: '+actionforfinfilenames:process(f,action)defprocess(filename,action):data=numpy.loadtxt(filename,delimiter=',')ifaction=='--min':values=numpy.min(data,axis=1)elifaction=='--mean':values=numpy.mean(data,axis=1)elifaction=='--max':values=numpy.max(data,axis=1)forminvalues:print(m)if__name__=='__main__':main()

This is four lines longer than its predecessor,
but broken into more digestible chunks of 8 and 12 lines.

Handling Standard Input

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:

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:

$ python ../code/count_stdin.py < small-01.csv

2 lines in standard input

A common mistake is to try to run something that reads from standard input like this:

$ python ../code/count_stdin.py small-01.csv

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.

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.
Only main changes:

$ cat ../code/readings_06.py

importsysimportnumpydefmain():script=sys.argv[0]action=sys.argv[1]filenames=sys.argv[2:]assertactionin['--min','--mean','--max'], \
'Action is not one of --min, --mean, or --max: '+actioniflen(filenames)==0:process(sys.stdin,action)else:forfinfilenames:process(f,action)defprocess(filename,action):data=numpy.loadtxt(filename,delimiter=',')ifaction=='--min':values=numpy.min(data,axis=1)elifaction=='--mean':values=numpy.mean(data,axis=1)elifaction=='--max':values=numpy.max(data,axis=1)forminvalues:print(m)if__name__=='__main__':main()

Let’s try it out:

$ python ../code/readings_06.py --mean < small-01.csv

0.333333333333
1.0

That’s better.
In fact,
that’s done:
the program now does everything we set out to do.

Finding Particular Files

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:

$ python my_ls.py py

left.py
right.py
zero.py

Solution

importsysimportglobdefmain():'''prints names of all files with sys.argv as suffix'''assertlen(sys.argv)>=2,'Argument list cannot be empty'suffix=sys.argv[1]# NB: behaviour is not as you'd expect if sys.argv[1] is *glob_input='*.'+suffix# construct the inputglob_output=sorted(glob.glob(glob_input))# call the glob functionforiteminglob_output:# print the outputprint(item)returnmain()

Changing Flags

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?

Solution

importsysimportnumpydefmain():script=sys.argv[0]action=sys.argv[1]filenames=sys.argv[2:]assertactionin['-n','-m','-x'], \
'Action is not one of -n, -m, or -x: '+actioniflen(filenames)==0:process(sys.stdin,action)else:forfinfilenames:process(f,action)defprocess(filename,action):data=numpy.loadtxt(filename,delimiter=',')ifaction=='-n':values=numpy.min(data,axis=1)elifaction=='-m':values=numpy.mean(data,axis=1)elifaction=='-x':values=numpy.max(data,axis=1)forminvalues:print(m)main()

Adding a Help Message

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.

Solution

# this is code/readings_08.pyimportsysimportnumpydefmain():script=sys.argv[0]iflen(sys.argv)==1:# no arguments, so print help messageprint("""Usage: python readings_08.py action filenames
action must be one of --min --mean --max
if filenames is blank, input is taken from stdin;
otherwise, each filename in the list of arguments is processed in turn""")returnaction=sys.argv[1]filenames=sys.argv[2:]assertactionin['--min','--mean','--max'], \
'Action is not one of --min, --mean, or --max: '+actioniflen(filenames)==0:process(sys.stdin,action)else:forfinfilenames:process(f,action)defprocess(filename,action):data=numpy.loadtxt(filename,delimiter=',')ifaction=='--min':values=numpy.min(data,axis=1)elifaction=='--mean':values=numpy.mean(data,axis=1)elifaction=='--max':values=numpy.max(data,axis=1)forminvalues:print(m)main()

Adding a Default Action

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

Solution

importsysimportnumpydefmain():script=sys.argv[0]action=sys.argv[1]ifactionnotin['--min','--mean','--max']:# if no action givenaction='--mean'# set a default action, that being meanfilenames=sys.argv[1:]# start the filenames one place earlier in the argv listelse:filenames=sys.argv[2:]iflen(filenames)==0:process(sys.stdin,action)else:forfinfilenames:process(f,action)defprocess(filename,action):data=numpy.loadtxt(filename,delimiter=',')ifaction=='--min':values=numpy.min(data,axis=1)elifaction=='--mean':values=numpy.mean(data,axis=1)elifaction=='--max':values=numpy.max(data,axis=1)forminvalues:print(m)main()

A File-Checker

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?

Solution

importsysimportnumpydefmain():script=sys.argv[0]filenames=sys.argv[1:]iflen(filenames)<=1:#nothing to checkprint('Only 1 file specified on input')else:nrow0,ncol0=row_col_count(filenames[0])print('First file %s: %d rows and %d columns'%(filenames[0],nrow0,ncol0))forfinfilenames[1:]:nrow,ncol=row_col_count(f)ifnrow!=nrow0orncol!=ncol0:print('File %s does not check: %d rows and %d columns'%(f,nrow,ncol))else:print('File %s checks'%f)returndefrow_col_count(filename):try:nrow,ncol=numpy.loadtxt(filename,delimiter=',').shapeexceptValueError:# 'ValueError' error is raised when numpy encounters lines that# have different number of data elements in them than the rest of the lines,# or when lines have non-numeric elementsnrow,ncol=(0,0)returnnrow,ncolmain()

Counting Lines

Write a program called line_count.py that works like the Unix wc command:

If no filenames are given, it reports the number of lines in standard input.

If one or more filenames are given, it reports the number of lines in each,
followed by the total number of lines.

Solution

importsysdefmain():'''print each input filename and the number of lines in it,
and print the sum of the number of lines'''filenames=sys.argv[1:]sum_nlines=0#initialize counting variableiflen(filenames)==0:# no filenames, just stdinsum_nlines=count_file_like(sys.stdin)print('stdin: %d'%sum_nlines)else:forfinfilenames:n=count_file(f)print('%s %d'%(f,n))sum_nlines+=nprint('total: %d'%sum_nlines)defcount_file(filename):'''count the number of lines in a file'''f=open(filename,'r')nlines=len(f.readlines())f.close()return(nlines)defcount_file_like(file_like):'''count the number of lines in a file-like object (eg stdin)'''n=0forlineinfile_like:n=n+1returnnmain()

Generate an Error Message

Write a program called check_arguments.py that prints usage
then exits the program if no arguments are provided.
(Hint: You can use sys.exit() to exit the program.)

$ python check_arguments.py

usage: python check_argument.py filename.txt

$ python check_arguments.py filename.txt

Thanks for specifying arguments!

Key Points

The sys library connects a Python program to the system it is running on.

The list sys.argv contains the command-line arguments that a program was run with.